-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauth.go
88 lines (79 loc) · 1.73 KB
/
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
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
package main
import (
"fmt"
"net/http"
"os"
"strings"
"github.com/bgentry/speakeasy"
"github.com/codegangsta/cli"
"github.com/modouwifi/md/api"
)
var cmdLogin = cli.Command{
Name: "login",
Usage: "log in of modou",
Action: runLogin,
}
func runLogin(c *cli.Context) {
// NOTE: gopass doesn't support multi-byte chars on Windows
password, err := readPassword("Enter password: ")
switch {
case err == nil:
case err.Error() == "unexpected newline":
fmt.Println("password is required.")
default:
fmt.Println(err.Error())
}
err = attemptLogin(password)
}
var cmdLogout = cli.Command{
Name: "logout",
Usage: "log out of modou",
Action: runLogout,
}
func runLogout(c *cli.Context) {
}
func readPassword(prompt string) (password string, err error) {
if acceptPasswordFromStdin && !IsTerminal(os.Stdin) {
_, err = fmt.Scanln(&password)
return
}
// NOTE: speakeasy may not support multi-byte chars on Windows
return speakeasy.Ask("Enter password: ")
}
func attemptLogin(password string) error {
req, err := client.NewRequest("POST", "/auth/login")
if err != nil {
return err
}
body := struct {
Password string `json:"password"`
}{
Password: password,
}
req.Body(body)
var result api.ResponseMessage
err = req.ToJSON(&result)
if err != nil {
return err
}
if result.Code != 0 {
fmt.Println(result.Msg)
} else {
res := req.GetRes()
rawCookie := res.Header.Get("Set-Cookie")
if rawCookie != "" {
strs := strings.Split(rawCookie, ";")
cookie := strings.Split(strs[0], "=")
path := strings.Split(strs[1], "=")[1]
config.Cookie = &http.Cookie{
Name: cookie[0],
Value: cookie[1],
Path: path,
}
config.Password = password
err = config.Write()
return err
}
}
return nil
}