ovpn-certman/handlers/auth.go

76 lines
1.7 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-03 18:14:47 +01:00
func OAuth2Endpoint(p *services.Provider, config *oauth2.Config) 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
2018-02-03 18:14:47 +01:00
accessToken, err := config.Exchange(oauth2.NoContext, code)
2018-02-01 09:31:06 +01:00
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
2018-02-03 18:14:47 +01:00
httpClient := config.Client(oauth2.NoContext, accessToken)
2018-02-03 18:14:47 +01:00
apiRequest, err := http.NewRequest("GET", os.Getenv("USER_ENDPOINT"), 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-03 18:14:47 +01:00
func GetLoginHandler(p *services.Provider, config *oauth2.Config) http.HandlerFunc {
2018-02-01 09:31:06 +01:00
return func(w http.ResponseWriter, req *http.Request) {
2018-02-03 18:14:47 +01:00
authURL := config.AuthCodeURL("", oauth2.AccessTypeOnline)
2018-02-01 09:31:06 +01:00
http.Redirect(w, req, authURL, http.StatusFound)
2018-02-01 03:30:00 +01:00
}
}