forked from Ptt-official-app/Ptt-backend
/
route_token.go
94 lines (73 loc) · 1.76 KB
/
route_token.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
package main
import (
"encoding/json"
"fmt"
"github.com/PichuChen/go-bbs"
"log"
"net/http"
"strings"
)
func routeToken(w http.ResponseWriter, r *http.Request) {
// TODO: Check IP Flowspeed
if r.Method == "POST" {
postToken(w, r)
return
}
}
func postToken(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
username := r.FormValue("username")
password := r.FormValue("password")
userec, err := findUserecById(username)
if err != nil {
m := map[string]string{
"error": "grant_error",
"error_description": err.Error(),
}
b, _ := json.MarshalIndent(m, "", " ")
w.Write(b)
return
}
log.Println("found user:", userec)
err = verifyPassword(userec, password)
if err != nil {
// TODO: add delay, warning, notify user
m := map[string]string{
"error": "grant_error",
"error_description": err.Error(),
}
b, _ := json.MarshalIndent(m, "", " ")
w.WriteHeader(http.StatusUnauthorized)
w.Write(b)
return
}
// Generate Access Token
token := newAccessTokenWithUsername(username)
m := map[string]string{
"access_token": token,
"token_type": "bearer",
}
b, _ := json.MarshalIndent(m, "", " ")
w.Write(b)
}
func findUserecById(userid string) (bbs.UserRecord, error) {
for _, it := range userRecs {
if userid == it.UserId() {
return it, nil
}
}
return nil, fmt.Errorf("user record not found")
}
func verifyPassword(userec bbs.UserRecord, password string) error {
log.Println("password", userec.HashedPassword())
return userec.VerifyPassword(password)
}
func getTokenFromRequest(r *http.Request) string {
a := r.Header.Get("Authorization")
s := strings.Split(a, " ")
if len(s) < 2 {
logger.Warningf("getTokenFromRequest error: len(s) < 2, got: %v", len(s))
return ""
}
return s[1]
}