86 lines
2.0 KiB
Go
86 lines
2.0 KiB
Go
package auth
|
|
|
|
import (
|
|
"server/models"
|
|
)
|
|
|
|
// CodeLogin 通过已校验的验证码完成登录,登录态结构与 PasswordLogin 保持一致。
|
|
// identity 由调用方按手机号/邮箱查得并已完成验证码校验。
|
|
func CodeLogin(identity *models.AuthIdentity, clientID, ip, userAgent, amr, loginType string) (*LoginResult, error) {
|
|
if identity == nil {
|
|
return nil, ErrPasswordWrong
|
|
}
|
|
if err := checkIdentityStatus(identity); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
tenants, err := ListTenantOptions(identity.ID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(tenants) == 0 {
|
|
_ = writeLoginLog(0, identity.ID, accountOf(identity), "", clientID, loginType, amr, 0, ErrNoTenantBound.Error(), ip, userAgent)
|
|
return nil, ErrNoTenantBound
|
|
}
|
|
|
|
profile, err := BuildProfile(identity)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
result := &LoginResult{Tenants: tenants, Identity: profile}
|
|
|
|
targetTid := uint64(PendingTenantID)
|
|
if len(tenants) == 1 {
|
|
targetTid = tenants[0].Tid
|
|
}
|
|
sess, err := CreateSession(SessionInfo{
|
|
IdentityID: identity.ID,
|
|
Tid: targetTid,
|
|
ClientID: clientID,
|
|
IP: ip,
|
|
UserAgent: userAgent,
|
|
LoginType: loginType,
|
|
Amr: amr,
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
accessTTL := 0
|
|
if targetTid == PendingTenantID {
|
|
accessTTL = 600
|
|
result.NeedChooseTenant = true
|
|
}
|
|
|
|
tokens, err := IssueTokens(TokenIssue{
|
|
IdentityID: identity.ID,
|
|
Tid: targetTid,
|
|
ClientID: clientID,
|
|
Sid: sess.Sid,
|
|
Username: profile.Nickname,
|
|
Amr: amr,
|
|
AccessTTL: accessTTL,
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
result.Tokens = tokens
|
|
|
|
_ = writeLoginLog(targetTid, identity.ID, accountOf(identity), profile.Nickname, clientID, loginType, amr, 1, "登录成功", ip, userAgent)
|
|
return result, nil
|
|
}
|
|
|
|
func accountOf(identity *models.AuthIdentity) string {
|
|
if identity != nil && identity.Account != nil {
|
|
return *identity.Account
|
|
}
|
|
if identity != nil && identity.Mobile != nil {
|
|
return *identity.Mobile
|
|
}
|
|
if identity != nil && identity.Email != nil {
|
|
return *identity.Email
|
|
}
|
|
return ""
|
|
}
|