Skip to content

Commit

Permalink
fix(session): renamed Login/Logout/Register
Browse files Browse the repository at this point in the history
  • Loading branch information
cnlangzi committed Apr 17, 2024
1 parent fd32bde commit 0618133
Show file tree
Hide file tree
Showing 23 changed files with 175 additions and 166 deletions.
16 changes: 8 additions & 8 deletions auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ var (
defaultTOPTAccountName = "Auth"
defaultDHTEmail = "auth:email"
defaultDHTMobile = "auth:mobile"
defaultSignInCodeLen = 6
defaultSignInCodeTTL = 60 * time.Second
defaultLoginCodeLen = 6
defaultLoginCodeTTL = 60 * time.Second
)

var (
Expand All @@ -48,8 +48,8 @@ type Auth struct {
totpIssuer string
totpAccountName string

signInCodeLen int
signInCodeTTL time.Duration
loginCodeSize int
loginCodeTTL time.Duration

dhtEmail string
dhtMobile string
Expand Down Expand Up @@ -122,12 +122,12 @@ func New(db *sqle.DB, options ...Option) *Auth {
a.dhtMobile = defaultDHTMobile
}

if a.signInCodeLen < 1 {
a.signInCodeLen = defaultSignInCodeLen
if a.loginCodeSize < 1 {
a.loginCodeSize = defaultLoginCodeLen
}

if a.signInCodeTTL < 1 {
a.signInCodeTTL = defaultSignInCodeTTL
if a.loginCodeTTL < 1 {
a.loginCodeTTL = defaultLoginCodeTTL
}

return a
Expand Down
36 changes: 17 additions & 19 deletions auth_db.go
Original file line number Diff line number Diff line change
Expand Up @@ -709,61 +709,57 @@ func (a *Auth) getUserProfileData(ctx context.Context, userID shardid.ID) (Profi
return pd, nil
}

func (a *Auth) createSignInCode(ctx context.Context, userID shardid.ID, ip string) (string, error) {
code := randStr(a.signInCodeLen, dicNumber)
func (a *Auth) createLoginCode(ctx context.Context, userID shardid.ID, userIP string) (string, error) {
code := randStr(a.loginCodeSize, dicNumber)

now := time.Now()

_, err := a.db.On(userID).
ExecBuilder(ctx, a.createBuilder().
Insert("<prefix>signin_code").
Insert("<prefix>login_code").
Set("user_id", userID.Int64).
Set("hash", generateHash(a.hash(), code, "")).
Set("ip", ip).
Set("expires_on", now.Add(a.signInCodeTTL)).
Set("user_ip", userIP).
Set("expires_on", now.Add(a.loginCodeTTL)).
Set("created_at", now).
End())

if err != nil {
a.logger.Error("auth: createSignInCode",
a.logger.Error("auth: createloginCode",
slog.Int64("user_id", userID.Int64),
slog.Any("err", err))
return "", ErrBadDatabase
}
return code, nil
}

func (a *Auth) checkSignInCode(ctx context.Context, userID shardid.ID, code string) error {
func (a *Auth) getLoginCodeUserIP(ctx context.Context, userID shardid.ID, code string) (string, error) {
h := generateHash(a.hash(), code, "")

var count int
var userIP string
err := a.db.On(userID).
QueryRowBuilder(ctx, a.createBuilder().
Select("<prefix>signin_code", "count(user_id)").
Select("<prefix>login_code", "user_ip").
Where("user_id = {user_id} AND hash = {hash}").
Param("user_id", userID.Int64).
Param("hash", h)).
Scan(&count)
Scan(&userIP)

if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return ErrCodeNotMatched
return "", ErrCodeNotMatched
}
a.logger.Error("auth: checkSignInCode",
a.logger.Error("auth: checkloginCode",
slog.Int64("user_id", userID.Int64),
slog.String("code", code),
slog.Any("err", err))
return ErrBadDatabase
}

if count == 0 {
return ErrCodeNotMatched
return "", ErrBadDatabase
}

return nil
return userIP, nil
}

func (a *Auth) createSession(ctx context.Context, userID shardid.ID, firstName, lastName string) (Session, error) {
func (a *Auth) createSession(ctx context.Context, userID shardid.ID, firstName, lastName, userIP, userAgent string) (Session, error) {
s := Session{
UserID: userID.Int64,
FirstName: firstName,
Expand Down Expand Up @@ -810,6 +806,8 @@ func (a *Auth) createSession(ctx context.Context, userID shardid.ID, firstName,
Insert("<prefix>user_token").
Set("user_id", userID.Int64).
Set("hash", hashToken(s.RefreshToken)).
Set("user_ip", userID).
Set("user_agent", userAgent).
Set("expires_on", exp).
Set("created_at", now).
End())
Expand Down
16 changes: 8 additions & 8 deletions auth_signin.go → auth_login.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ import (
"errors"
)

// SignIn sign in with email and password.
func (a *Auth) SignIn(ctx context.Context, email, passwd string, option LoginOption) (Session, error) {
// Login sign in with email and password.
func (a *Auth) Login(ctx context.Context, email, passwd string, option LoginOption) (Session, error) {
u, err := a.getUserByEmail(ctx, email)

if err == nil {
if verifyHash(a.hash(), u.Passwd, passwd, u.Salt) {
return a.createSession(ctx, u.ID, u.FirstName, u.LastName)
return a.createSession(ctx, u.ID, u.FirstName, u.LastName, option.UserIP, option.UserAgent)
}

return noSession, ErrPasswdNotMatched
Expand All @@ -23,20 +23,20 @@ func (a *Auth) SignIn(ctx context.Context, email, passwd string, option LoginOpt
return noSession, err
}

return a.createSession(ctx, u.ID, u.FirstName, u.LastName)
return a.createSession(ctx, u.ID, u.FirstName, u.LastName, option.UserIP, option.UserAgent)
}

return noSession, err

}

// SignInMobile sign in with mobile and password.
func (a *Auth) SignInMobile(ctx context.Context, mobile, passwd string, option LoginOption) (Session, error) {
// LoginMobile sign in with mobile and password.
func (a *Auth) LoginMobile(ctx context.Context, mobile, passwd string, option LoginOption) (Session, error) {
u, err := a.getUserByMobile(ctx, mobile)

if err == nil {
if verifyHash(a.hash(), u.Passwd, passwd, u.Salt) {
return a.createSession(ctx, u.ID, u.FirstName, u.LastName)
return a.createSession(ctx, u.ID, u.FirstName, u.LastName, option.UserIP, option.UserAgent)
}

return noSession, ErrPasswdNotMatched
Expand All @@ -48,7 +48,7 @@ func (a *Auth) SignInMobile(ctx context.Context, mobile, passwd string, option L
return noSession, err
}

return a.createSession(ctx, u.ID, u.FirstName, u.LastName)
return a.createSession(ctx, u.ID, u.FirstName, u.LastName, option.UserIP, option.UserAgent)
}

return noSession, err
Expand Down
12 changes: 6 additions & 6 deletions auth_signin_test.go → auth_login_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import (
"github.com/yaitoo/sqle/shardid"
)

func TestSignIn(t *testing.T) {
func TestLogin(t *testing.T) {

authTest := createAuthTest("./tests_sign_in.db")
authTest := createAuthTest("./tests_login.db")

tests := []struct {
name string
Expand Down Expand Up @@ -73,7 +73,7 @@ func TestSignIn(t *testing.T) {
}
}

s, err := authTest.SignIn(context.TODO(), test.email, test.passwd, test.option)
s, err := authTest.Login(context.TODO(), test.email, test.passwd, test.option)
if test.wantedErr == nil {
require.NoError(t, err)
} else {
Expand All @@ -97,9 +97,9 @@ func TestSignIn(t *testing.T) {
}
}

func TestSignInMobile(t *testing.T) {
func TestLoginMobile(t *testing.T) {

authTest := createAuthTest("./tests_sign_in_mobile.db")
authTest := createAuthTest("./tests_login_mobile.db")

tests := []struct {
name string
Expand Down Expand Up @@ -173,7 +173,7 @@ func TestSignInMobile(t *testing.T) {
}
}

s, err := authTest.SignInMobile(context.TODO(), test.mobile, test.passwd, test.option)
s, err := authTest.LoginMobile(context.TODO(), test.mobile, test.passwd, test.option)
if test.wantedErr == nil {
require.NoError(t, err)
} else {
Expand Down
68 changes: 68 additions & 0 deletions auth_login_with_code.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package auth

import (
"context"
"errors"
)

// CreateLoginCode create a code for loging in by email
func (a *Auth) CreateLoginCode(ctx context.Context, email string, option LoginOption) (string, error) {
id, err := a.getUserIDByEmail(ctx, email)

if option.CreateIfNotExists && errors.Is(err, ErrEmailNotFound) {
u, err := a.createLoginWithEmail(ctx, email, randStr(12, dicAlphaNumber), option.FirstName, option.LastName)
if err != nil {
return "", err
}

id = u.ID
}

return a.createLoginCode(ctx, id, option.UserIP)
}

// LoginWithCode sign in with email and code.
func (a *Auth) LoginWithCode(ctx context.Context, email, code string) (Session, error) {
u, err := a.getUserByEmail(ctx, email)
if err != nil {
return noSession, err
}

userIP, err := a.getLoginCodeUserIP(ctx, u.ID, code)
if err != nil {
return noSession, err
}

return a.createSession(ctx, u.ID, u.FirstName, u.LastName, userIP, "CODE")
}

// CreateLoginMobileCode create a code for loging in by mobile
func (a *Auth) CreateLoginMobileCode(ctx context.Context, mobile string, option LoginOption) (string, error) {
id, err := a.getUserIDByMobile(ctx, mobile)

if option.CreateIfNotExists && errors.Is(err, ErrMobileNotFound) {
u, err := a.createLoginWithMobile(ctx, mobile, randStr(12, dicAlphaNumber), option.FirstName, option.LastName)
if err != nil {
return "", err
}

id = u.ID
}

return a.createLoginCode(ctx, id, option.UserIP)
}

// LoginMobileWithCode sign in with mobile and code.
func (a *Auth) LoginMobileWithCode(ctx context.Context, mobile, code string) (Session, error) {
u, err := a.getUserByMobile(ctx, mobile)
if err != nil {
return noSession, err
}

userIP, err := a.getLoginCodeUserIP(ctx, u.ID, code)
if err != nil {
return noSession, err
}

return a.createSession(ctx, u.ID, u.FirstName, u.LastName, userIP, "CODE")
}
20 changes: 10 additions & 10 deletions auth_signin_with_code_test.go → auth_login_with_code_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import (
"github.com/yaitoo/sqle/shardid"
)

func TestSignInWithCode(t *testing.T) {
func TestLoginWithCode(t *testing.T) {

authTest := createAuthTest("./tests_sign_in_with_code.db")
authTest := createAuthTest("./tests_login_with_code.db")

tests := []struct {
name string
Expand All @@ -32,7 +32,7 @@ func TestSignInWithCode(t *testing.T) {
email: "code_not_matched@sign_in_with_code.com",
wantedErr: ErrCodeNotMatched,
setup: func(r *require.Assertions) string {
_, err := authTest.CreateSignInCode(context.Background(), "code_not_matched@sign_in_with_code.com", LoginOption{CreateIfNotExists: true})
_, err := authTest.CreateLoginCode(context.Background(), "code_not_matched@sign_in_with_code.com", LoginOption{CreateIfNotExists: true})
r.NoError(err)

return ""
Expand All @@ -42,7 +42,7 @@ func TestSignInWithCode(t *testing.T) {
name: "code_should_work",
email: "code@sign_in_with_code.com",
setup: func(r *require.Assertions) string {
code, err := authTest.CreateSignInCode(context.Background(), "code@sign_in_with_code.com", LoginOption{CreateIfNotExists: true})
code, err := authTest.CreateLoginCode(context.Background(), "code@sign_in_with_code.com", LoginOption{CreateIfNotExists: true})
r.NoError(err)

return code
Expand All @@ -58,7 +58,7 @@ func TestSignInWithCode(t *testing.T) {

code := test.setup(r)

s, err := authTest.SignInWithCode(context.TODO(), test.email, code)
s, err := authTest.LoginWithCode(context.TODO(), test.email, code)
if test.wantedErr == nil {
require.NoError(t, err)
} else {
Expand All @@ -82,9 +82,9 @@ func TestSignInWithCode(t *testing.T) {
}
}

func TestSignInMobileWithCode(t *testing.T) {
func TestLoginMobileWithCode(t *testing.T) {

authTest := createAuthTest("./tests_sign_in_mobile_with_code.db")
authTest := createAuthTest("./tests_login_mobile_with_code.db")

tests := []struct {
name string
Expand All @@ -106,7 +106,7 @@ func TestSignInMobileWithCode(t *testing.T) {
mobile: "1+333444555",
wantedErr: ErrCodeNotMatched,
setup: func(r *require.Assertions) string {
_, err := authTest.CreateSignInMobileCode(context.Background(), "1+333444555", LoginOption{CreateIfNotExists: true})
_, err := authTest.CreateLoginMobileCode(context.Background(), "1+333444555", LoginOption{CreateIfNotExists: true})
r.NoError(err)

return ""
Expand All @@ -116,7 +116,7 @@ func TestSignInMobileWithCode(t *testing.T) {
name: "code_should_work",
mobile: "1+444555666",
setup: func(r *require.Assertions) string {
code, err := authTest.CreateSignInMobileCode(context.Background(), "1+444555666", LoginOption{CreateIfNotExists: true})
code, err := authTest.CreateLoginMobileCode(context.Background(), "1+444555666", LoginOption{CreateIfNotExists: true})
r.NoError(err)

return code
Expand All @@ -131,7 +131,7 @@ func TestSignInMobileWithCode(t *testing.T) {

code := test.setup(r)

s, err := authTest.SignInMobileWithCode(context.TODO(), test.mobile, code)
s, err := authTest.LoginMobileWithCode(context.TODO(), test.mobile, code)
if test.wantedErr == nil {
require.NoError(t, err)
} else {
Expand Down
12 changes: 6 additions & 6 deletions auth_signin_with_otp.go → auth_login_with_otp.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import (
"github.com/pquerna/otp/totp"
)

// SignInWithOTP sign in with email and otp.
func (a *Auth) SignInWithOTP(ctx context.Context, email, otp string) (Session, error) {
// LoginWithOTP sign in with email and otp.
func (a *Auth) LoginWithOTP(ctx context.Context, email, otp string) (Session, error) {

u, err := a.getUserByEmail(ctx, email)

Expand All @@ -24,12 +24,12 @@ func (a *Auth) SignInWithOTP(ctx context.Context, email, otp string) (Session, e
return noSession, ErrOTPNotMatched
}

return a.createSession(ctx, u.ID, u.FirstName, u.LastName)
return a.createSession(ctx, u.ID, u.FirstName, u.LastName, "", "OTP")

}

// SignInMobileWithOTP sign in with mobile and otp.
func (a *Auth) SignInMobileWithOTP(ctx context.Context, mobile, otp string) (Session, error) {
// LoginMobileWithOTP sign in with mobile and otp.
func (a *Auth) LoginMobileWithOTP(ctx context.Context, mobile, otp string) (Session, error) {
u, err := a.getUserByMobile(ctx, mobile)

if err != nil {
Expand All @@ -45,5 +45,5 @@ func (a *Auth) SignInMobileWithOTP(ctx context.Context, mobile, otp string) (Ses
return noSession, ErrOTPNotMatched
}

return a.createSession(ctx, u.ID, u.FirstName, u.LastName)
return a.createSession(ctx, u.ID, u.FirstName, u.LastName, "", "OTP")
}
Loading

0 comments on commit 0618133

Please sign in to comment.