-
Notifications
You must be signed in to change notification settings - Fork 8
/
login.go
85 lines (78 loc) · 2.04 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
package controllers
import (
"context"
"net/http"
"time"
"github.com/Github-Web-Apps/Starhub/config"
"github.com/Github-Web-Apps/Starhub/datastore"
"github.com/Github-Web-Apps/Starhub/oauth"
"github.com/gorilla/sessions"
)
// Login ctrl
type Login struct {
Base
oauth *oauth.Oauth
store datastore.Datastore
}
// NewLogin ctrl
func NewLogin(
config config.Config,
session sessions.Store,
oauth *oauth.Oauth,
store datastore.Datastore,
) *Login {
return &Login{
Base: Base{
config: config,
session: session,
},
store: store,
oauth: oauth,
}
}
// Handler handles /
func (ctrl *Login) Handler(w http.ResponseWriter, r *http.Request) {
var url = ctrl.oauth.AuthCodeURL()
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
// CallbackHandler handles /login/callback
func (ctrl *Login) CallbackHandler(w http.ResponseWriter, r *http.Request) {
var state = r.FormValue("state")
var code = r.FormValue("code")
var ctx = context.Background()
if !ctrl.oauth.IsStateValid(state) {
http.Error(w, "invalid oauth state", http.StatusUnauthorized)
return
}
token, err := ctrl.oauth.Exchange(ctx, code)
if err != nil {
http.Error(w, err.Error(), http.StatusUnauthorized)
return
}
var client = ctrl.oauth.Client(ctx, token)
u, _, err := client.Users.Get(ctx, "")
if err != nil {
http.Error(w, err.Error(), http.StatusUnauthorized)
return
}
exists, _ := ctrl.store.UserExist(int64(*u.ID))
if err := ctrl.store.SaveToken(int64(*u.ID), token); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !exists {
if err := ctrl.store.Schedule(int64(*u.ID), time.Now()); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
session, _ := ctrl.session.Get(r, ctrl.config.SessionName)
session.Values["user_id"] = *u.ID
session.Values["user_login"] = *u.Login
session.Values["new_user"] = !exists
if err := session.Save(r, w); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
}