forked from osuripple/hanayo
-
Notifications
You must be signed in to change notification settings - Fork 3
/
login.go
210 lines (186 loc) · 5.1 KB
/
login.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package main
import (
"database/sql"
"html/template"
"net/http"
"strconv"
"strings"
"time"
"net/url"
"github.com/gin-gonic/gin"
"golang.org/x/crypto/bcrypt"
"github.com/kawatapw/api/common"
"zxq.co/x/rs"
)
func loginSubmit(c *gin.Context) {
if getContext(c).User.ID != 0 {
simpleReply(c, errorMessage{T(c, "You're already logged in!")})
return
}
if c.PostForm("username") == "" || c.PostForm("password") == "" {
simpleReply(c, errorMessage{T(c, "Username or password not set.")})
return
}
param := "username_safe"
u := c.PostForm("username")
if strings.Contains(u, "@") {
param = "email"
} else {
u = safeUsername(u)
}
var data struct {
ID int
Username string
Password string
PasswordVersion int
Country string
pRaw int64
Privileges common.UserPrivileges
Flags uint
}
err := db.QueryRow(`
SELECT
u.id, u.password_md5,
u.username, u.password_version,
s.country, u.privileges, u.flags
FROM users u
LEFT JOIN users_stats s ON s.id = u.id
WHERE u.`+param+` = ? LIMIT 1`, strings.TrimSpace(u)).Scan(
&data.ID, &data.Password,
&data.Username, &data.PasswordVersion,
&data.Country, &data.pRaw, &data.Flags,
)
data.Privileges = common.UserPrivileges(data.pRaw)
switch {
case err == sql.ErrNoRows:
if param == "username_safe" {
param = "username"
}
simpleReply(c, errorMessage{T(c, "No user with such %s!", param)})
return
case err != nil:
c.Error(err)
resp500(c)
return
}
if data.PasswordVersion == 1 {
addMessage(c, warningMessage{T(c, "Your password is sooooooo old, that we don't even know how to deal with it anymore. Could you please change it?")})
c.Redirect(302, "/pwreset")
return
}
if err := bcrypt.CompareHashAndPassword(
[]byte(data.Password),
[]byte(cmd5(c.PostForm("password"))),
); err != nil {
simpleReply(c, errorMessage{T(c, "Wrong password.")})
return
}
// update password if cost is < bcrypt.DefaultCost
if i, err := bcrypt.Cost([]byte(data.Password)); err == nil && i < bcrypt.DefaultCost {
pass, err := bcrypt.GenerateFromPassword([]byte(cmd5(c.PostForm("password"))), bcrypt.DefaultCost)
if err == nil {
if _, err := db.Exec("UPDATE users SET password_md5 = ? WHERE id = ?", string(pass), data.ID); err == nil {
data.Password = string(pass)
}
}
}
sess := getSession(c)
if data.Privileges&common.UserPrivilegePendingVerification > 0 {
setYCookie(data.ID, c)
addMessage(c, warningMessage{T(c, "You will need to verify your account first.")})
sess.Save()
c.Redirect(302, "/register/verify?u="+strconv.Itoa(data.ID))
return
}
if data.Privileges&common.UserPrivilegeNormal == 0 {
simpleReply(c, errorMessage{T(c, "You are not allowed to login. This means your account is either banned or locked.")})
return
}
setYCookie(data.ID, c)
sess.Set("userid", data.ID)
sess.Set("pw", cmd5(data.Password))
sess.Set("logout", rs.String(15))
tfaEnabled := is2faEnabled(data.ID)
if tfaEnabled == 0 {
afterLogin(c, data.ID, data.Country, data.Flags)
} else {
sess.Set("2fa_must_validate", true)
}
redir := c.PostForm("redir")
if len(redir) > 0 && redir[0] != '/' {
redir = ""
}
if tfaEnabled > 0 {
sess.Save()
c.Redirect(302, "/2fa_gateway?redir="+url.QueryEscape(redir))
} else {
addMessage(c, successMessage{T(c, "Hey %s! You are now logged in.", template.HTMLEscapeString(data.Username))})
sess.Save()
if redir == "" {
redir = "/"
}
c.Redirect(302, redir)
}
return
}
func afterLogin(c *gin.Context, id int, country string, flags uint) {
s, err := generateToken(id, c)
if err != nil {
resp500(c)
c.Error(err)
return
}
getSession(c).Set("token", s)
if country == "XX" {
setCountry(c, id)
}
logIP(c, id)
}
func safeUsername(u string) string {
return strings.Replace(strings.TrimSpace(strings.ToLower(u)), " ", "_", -1)
}
func logout(c *gin.Context) {
ctx := getContext(c)
if ctx.User.ID == 0 {
respEmpty(c, "Log out", warningMessage{T(c, "You're already logged out!")})
return
}
sess := getSession(c)
s, _ := sess.Get("logout").(string)
if s != c.Query("k") {
// todo: return "are you sure you want to log out?" page
respEmpty(c, "Log out", warningMessage{T(c, "Your session has expired. Please try redoing what you were trying to do.")})
return
}
sess.Clear()
http.SetCookie(c.Writer, &http.Cookie{
Name: "rt",
Value: "",
Expires: time.Now().Add(-time.Hour),
})
addMessage(c, successMessage{T(c, "Successfully logged out.")})
sess.Save()
c.Redirect(302, "/")
}
func generateToken(id int, c *gin.Context) (string, error) {
tok := common.RandomString(32)
_, err := db.Exec(
`INSERT INTO tokens(user, privileges, description, token, private)
VALUES ( ?, '0', ?, ?, '1');`,
id, clientIP(c), cmd5(tok))
if err != nil {
return "", err
}
return tok, nil
}
func checkToken(s string, id int, c *gin.Context) (string, error) {
if s == "" {
return generateToken(id, c)
}
if err := db.QueryRow("SELECT 1 FROM tokens WHERE token = ?", cmd5(s)).Scan(new(int)); err == sql.ErrNoRows {
return generateToken(id, c)
} else if err != nil {
return "", err
}
return s, nil
}