renamed site directory to server
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"ruben/inventory2/internal/domains/authentication"
|
||||
"ruben/inventory2/internal/server/cookies"
|
||||
"ruben/inventory2/internal/server/response"
|
||||
)
|
||||
|
||||
// TODO: use a login/logout server? (prefix: '/auth'?)
|
||||
|
||||
// GET /login
|
||||
func (s *Server) loginPage(r *http.Request) (response.Response, error) {
|
||||
ctx := r.Context()
|
||||
|
||||
u, err := newLoginURL(ctx, s.auth, "/")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return response.TemporaryRedirect(u), nil
|
||||
}
|
||||
|
||||
func newLoginURL(ctx context.Context, auth *authentication.Authenticator, targetURI string) (string, error) {
|
||||
state, err := auth.NewState(ctx, targetURI)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to generate random state: %w", err)
|
||||
}
|
||||
|
||||
base64EncodedState := fmt.Sprintf("%x", state[:])
|
||||
|
||||
return auth.AuthCodeURL(base64EncodedState), nil
|
||||
}
|
||||
|
||||
// GET /login/callback
|
||||
func (s *Server) loginCallback(r *http.Request) (response.Response, error) {
|
||||
ctx := r.Context()
|
||||
q := r.URL.Query()
|
||||
|
||||
// obtain token and profile
|
||||
|
||||
accessToken, targetURI, expiration, err := s.auth.Exchange(ctx, q.Get("state"), q.Get("code"))
|
||||
if err != nil {
|
||||
return nil, response.Unauthorized().
|
||||
Msg(fmt.Sprintf("Failed to exchange an authorization code for a token")).
|
||||
Wrap(err)
|
||||
}
|
||||
|
||||
// set access_token cookie and redirect to a reasonable place
|
||||
|
||||
return response.TemporaryRedirect(targetURI).
|
||||
Cookie(cookies.AccessToken(accessToken, expiration)), nil
|
||||
}
|
||||
|
||||
// GET /logout
|
||||
func (s *Server) logoutPage(r *http.Request) (response.Response, error) {
|
||||
host := r.Header.Get("X-Forwarded-Host")
|
||||
if host == "" {
|
||||
host = r.Host
|
||||
}
|
||||
|
||||
if ck, err := r.Cookie("access_token"); err == nil && ck != nil {
|
||||
if err := s.auth.DeleteOAuthTokens(r.Context(), ck.Value); err != nil {
|
||||
fmt.Println("[ERROR] failed to delete auth token:", err)
|
||||
}
|
||||
}
|
||||
|
||||
return response.TemporaryRedirect(s.auth.GetLogoutURL(host).String()).
|
||||
Cookie(cookies.Expired("access_token")), nil
|
||||
}
|
||||
Reference in New Issue
Block a user