-
Notifications
You must be signed in to change notification settings - Fork 5
/
basic_auth.go
61 lines (52 loc) · 1.45 KB
/
basic_auth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package auth
import (
"context"
"fmt"
"time"
logging "github.com/ipfs/go-log/v2"
"github.com/jiaozifs/jiaozifs/models"
"golang.org/x/crypto/bcrypt"
)
var log = logging.Logger("auth")
type Register struct {
Username string `json:"username"`
Email string `json:"email"`
Password string `json:"password"`
}
func (r *Register) Register(ctx context.Context, repo models.IUserRepo) error {
// check username, email
count1, err := repo.Count(ctx, models.NewCountUserParam().SetName(r.Username))
if err != nil {
return err
}
count2, err := repo.Count(ctx, models.NewCountUserParam().SetName(r.Email))
if err != nil {
return err
}
if count1+count2 > 0 {
return fmt.Errorf("username %s or email %s not found %w ", r.Username, r.Email, ErrInvalidNameEmail)
}
// reserve temporarily
password, err := bcrypt.GenerateFromPassword([]byte(r.Password), passwordCost)
if err != nil {
return fmt.Errorf("invalid password %w", err)
}
// insert db
user := &models.User{
Name: r.Username,
Email: r.Email,
EncryptedPassword: string(password),
CurrentSignInAt: time.Time{},
LastSignInAt: time.Time{},
CurrentSignInIP: "",
LastSignInIP: "",
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
insertUser, err := repo.Insert(ctx, user)
if err != nil {
return fmt.Errorf("inser user %s user error %w", r.Username, err)
}
log.Infof("%s registration success", insertUser.Name)
return nil
}