💾 Archived View for gemini.rmf-dev.com › repo › Vaati › Gemigit › files › 5cce258f978b5b1166223bd4f1… captured on 2023-09-08 at 16:26:38. Gemini links have been rewritten to link to archived content
⬅️ Previous capture (2023-05-24)
-=-=-=-=-=-=-
0 package auth
1
2 import (
3 "errors"
4 "gemigit/config"
5 "gemigit/db"
6 "gemigit/access"
7 "time"
8
9 "github.com/pquerna/otp/totp"
10 )
11
12 var userAttempts = make(map[string]int)
13 var clientAttempts = make(map[string]int)
14 var registrationAttempts = make(map[string]int)
15 var loginToken = make(map[string]db.User)
16
17 func Decrease() {
18 for {
19 userAttempts = make(map[string]int)
20 clientAttempts = make(map[string]int)
21 registrationAttempts = make(map[string]int)
22 loginToken = make(map[string]db.User)
23 time.Sleep(time.Duration(config.Cfg.Protection.Reset) *
24 time.Second)
25 }
26 }
27
28 func try(attemps *map[string]int, key string, max int) bool {
29 value, exist := (*attemps)[key]
30 if exist {
31 if value < max {
32 (*attemps)[key]++
33 } else {
34 return true
35 }
36 } else {
37 (*attemps)[key] = 1
38 }
39 return false
40 }
41
42 // Check if credential are valid then add client signature
43 // as a connected user
44 func Connect(username string, password string,
45 signature string, ip string) error {
46
47 if try(&userAttempts, username, config.Cfg.Protection.Account) {
48 return errors.New("the account is locked, " +
49 "too many connections attempts")
50 }
51
52 if try(&clientAttempts, ip, config.Cfg.Protection.Ip) {
53 return errors.New("too many connections attempts")
54 }
55
56 err := access.Login(username, password, false, true)
57 if err != nil {
58 return err
59 }
60
61 user, err := db.FetchUser(username, signature)
62 if err == nil {
63 if user.Secret != "" {
64 loginToken[signature] = user
65 return errors.New("token required")
66 }
67 user.CreateSession(signature)
68 return nil
69 }
70 if !config.Cfg.Ldap.Enabled {
71 return err
72 }
73 err = db.Register(username, "")
74 if err != nil {
75 return err
76 }
77 user, err = db.FetchUser(username, signature)
78 if err != nil {
79 return err
80 }
81 user.CreateSession(signature)
82 return nil
83 }
84
85 func Register(username string, password string, ip string) error {
86 if try(®istrationAttempts, ip, config.Cfg.Protection.Registration) {
87 return errors.New("too many registration attempts")
88 }
89 return db.Register(username, password)
90 }
91
92 func LoginOTP(signature string, code string) error {
93 user, exist := loginToken[signature]
94 if !exist {
95 return errors.New("invalid request")
96 }
97 if !totp.Validate(code, user.Secret) {
98 return errors.New("wrong code")
99 }
100 user.CreateSession(signature)
101 delete(loginToken, signature)
102 return nil
103 }
104