ovpn-certman/handlers/auth.go

87 lines
2 KiB
Go
Raw Normal View History

2018-01-29 09:18:19 +01:00
package handlers
import (
2018-02-01 09:31:06 +01:00
"encoding/json"
2018-02-01 03:30:00 +01:00
"fmt"
2018-01-29 09:18:19 +01:00
"net/http"
2018-02-01 09:31:06 +01:00
"os"
2018-02-01 03:30:00 +01:00
"git.klink.asia/paul/certman/views"
2018-02-01 09:31:06 +01:00
"golang.org/x/oauth2"
2018-01-29 09:18:19 +01:00
"git.klink.asia/paul/certman/services"
)
2018-02-01 09:31:06 +01:00
var GitlabConfig = &oauth2.Config{
ClientID: os.Getenv("OAUTH2_CLIENT_ID"),
ClientSecret: os.Getenv("OAUTH2_CLIENT_SECRET"),
Scopes: []string{"read_user"},
RedirectURL: os.Getenv("HOST") + "/login/oauth2/redirect",
Endpoint: oauth2.Endpoint{
AuthURL: os.Getenv("OAUTH2_AUTH_URL"),
TokenURL: os.Getenv("OAUTH2_TOKEN_URL"),
},
}
2018-01-29 09:18:19 +01:00
2018-02-01 09:31:06 +01:00
func OAuth2Endpoint(p *services.Provider) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
2018-02-01 09:31:06 +01:00
v := views.NewWithSession(req, p.Sessions)
2018-02-01 09:31:06 +01:00
code := req.FormValue("code")
2018-02-01 09:31:06 +01:00
// exchange code for token
accessToken, err := GitlabConfig.Exchange(oauth2.NoContext, code)
if err != nil {
fmt.Println(err)
http.NotFound(w, req)
return
}
2018-02-01 09:31:06 +01:00
if accessToken.Valid() {
// generate a client using the access token
httpClient := GitlabConfig.Client(oauth2.NoContext, accessToken)
2018-02-01 09:31:06 +01:00
apiRequest, err := http.NewRequest("GET", "https://git.klink.asia/api/v4/user", nil)
2018-02-01 03:30:00 +01:00
if err != nil {
2018-02-01 09:31:06 +01:00
v.RenderError(w, http.StatusNotFound)
2018-02-01 03:30:00 +01:00
return
}
2018-02-01 09:31:06 +01:00
resp, err := httpClient.Do(apiRequest)
2018-02-01 03:30:00 +01:00
if err != nil {
2018-02-01 09:31:06 +01:00
fmt.Println(err.Error())
v.RenderError(w, http.StatusInternalServerError)
2018-02-01 03:30:00 +01:00
return
}
2018-02-01 09:31:06 +01:00
var user struct {
Username string `json:"username"`
}
2018-02-01 03:30:00 +01:00
2018-02-01 09:31:06 +01:00
err = json.NewDecoder(resp.Body).Decode(&user)
2018-02-01 03:30:00 +01:00
if err != nil {
2018-02-01 09:31:06 +01:00
fmt.Println(err.Error())
v.RenderError(w, http.StatusInternalServerError)
2018-02-01 03:30:00 +01:00
return
}
2018-02-01 09:31:06 +01:00
if user.Username != "" {
p.Sessions.SetUsername(w, req, user.Username)
http.Redirect(w, req, "/certs", http.StatusFound)
return
}
2018-02-01 03:30:00 +01:00
2018-02-01 09:31:06 +01:00
fmt.Println(err.Error())
v.RenderError(w, http.StatusInternalServerError)
return
2018-02-01 03:30:00 +01:00
}
}
}
2018-02-01 09:31:06 +01:00
func GetLoginHandler(p *services.Provider) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
authURL := GitlabConfig.AuthCodeURL("", oauth2.AccessTypeOnline)
http.Redirect(w, req, authURL, http.StatusFound)
2018-02-01 03:30:00 +01:00
}
}