-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
15 changed files
with
502 additions
and
40 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,118 @@ | ||
// Package api contains the authentication endpoints. | ||
package api | ||
|
||
import ( | ||
"encoding/json" | ||
"errors" | ||
"net/http" | ||
|
||
"log/slog" | ||
|
||
"github.com/go-chi/chi/v5" | ||
"github.com/perebaj/contractus" | ||
"golang.org/x/oauth2" | ||
) | ||
|
||
// Auth endpoints | ||
|
||
// TODO(JOJO): randomize this | ||
var randState = "random" | ||
|
||
// RegisterAuthHandler register the auth endpoints. | ||
func RegisterAuthHandler(r chi.Router, a Auth) { | ||
const ( | ||
loginURL = "/" | ||
callbackURL = "/callback" | ||
tokenURL = "/token" | ||
) | ||
r.Method(http.MethodGet, loginURL, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
login(w, r, a) | ||
})) | ||
r.Method(http.MethodGet, callbackURL, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
callback(w, r, a) | ||
})) | ||
r.Method(http.MethodGet, tokenURL, http.HandlerFunc(token)) | ||
} | ||
|
||
func login(w http.ResponseWriter, r *http.Request, a Auth) { | ||
var url string | ||
if a.AccessType == "online" { | ||
url = a.GoogleOAuthConfig.AuthCodeURL(randState, oauth2.AccessTypeOnline) | ||
} else { | ||
url = a.GoogleOAuthConfig.AuthCodeURL(randState, oauth2.AccessTypeOffline) | ||
} | ||
|
||
http.Redirect(w, r, url, http.StatusFound) | ||
slog.Info("login request received") | ||
} | ||
|
||
func callback(w http.ResponseWriter, r *http.Request, a Auth) { | ||
state := r.FormValue("state") | ||
if state == "" { | ||
sendErr(w, http.StatusBadRequest, errors.New("missing state")) | ||
return | ||
} | ||
if state != randState { | ||
sendErr(w, http.StatusBadRequest, errors.New("invalid state")) | ||
return | ||
} | ||
|
||
code := r.FormValue("code") | ||
if code == "" { | ||
sendErr(w, http.StatusBadRequest, errors.New("missing code")) | ||
return | ||
} | ||
|
||
ctx := r.Context() | ||
token, err := a.GoogleOAuthConfig.Exchange(ctx, code) | ||
if err != nil { | ||
sendErr(w, http.StatusInternalServerError, err) | ||
return | ||
} | ||
|
||
client := a.GoogleOAuthConfig.Client(ctx, token) | ||
resp, err := client.Get("https://www.googleapis.com/oauth2/v2/userinfo") | ||
if err != nil { | ||
sendErr(w, http.StatusInternalServerError, err) | ||
return | ||
} | ||
defer func() { | ||
_ = resp.Body.Close() | ||
}() | ||
|
||
d := json.NewDecoder(resp.Body) | ||
|
||
var usr contractus.GoogleUser | ||
err = d.Decode(&usr) | ||
if err != nil { | ||
sendErr(w, http.StatusInternalServerError, err) | ||
return | ||
} | ||
|
||
tokenString, err := a.GenerateToken(usr.Email) | ||
if err != nil { | ||
sendErr(w, http.StatusInternalServerError, err) | ||
return | ||
} | ||
|
||
cookie := http.Cookie{ | ||
Name: "jwt", | ||
Value: tokenString, | ||
MaxAge: 60 * 60 * 24 * 7, // 1 week | ||
Domain: a.Domain, | ||
} | ||
http.SetCookie(w, &cookie) | ||
http.Redirect(w, r, a.Domain+"/docs", http.StatusSeeOther) | ||
} | ||
|
||
func token(w http.ResponseWriter, r *http.Request) { | ||
jwt, err := r.Cookie("jwt") | ||
if err != nil { | ||
sendErr(w, http.StatusUnauthorized, Error{"login_again", "try to log in again"}) | ||
return | ||
} | ||
|
||
send(w, http.StatusOK, struct { | ||
Token string `json:"token"` | ||
}{jwt.Value}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
package api | ||
|
||
import ( | ||
"encoding/json" | ||
"net/http" | ||
"net/http/httptest" | ||
"testing" | ||
|
||
"github.com/go-chi/chi/v5" | ||
"golang.org/x/oauth2" | ||
"golang.org/x/oauth2/google" | ||
) | ||
|
||
func TestToken(t *testing.T) { | ||
r := chi.NewRouter() | ||
RegisterAuthHandler(r, Auth{}) | ||
|
||
wantToken := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxMjN9.PZLMJBT9OIVG2qgp9hQr685oVYFgRgWpcSPmNcw6y7M" | ||
req := httptest.NewRequest(http.MethodGet, "/token", nil) | ||
req.AddCookie(&http.Cookie{ | ||
Name: "jwt", | ||
Value: wantToken, | ||
}) | ||
|
||
resp := httptest.NewRecorder() | ||
r.ServeHTTP(resp, req) | ||
|
||
var response struct { | ||
Token string `json:"token"` | ||
} | ||
|
||
if err := json.NewDecoder(resp.Body).Decode(&response); err != nil { | ||
t.Fatalf("failed to decode response body: %v", err) | ||
} | ||
assert(t, resp.Code, http.StatusOK) | ||
assert(t, response.Token, wantToken) | ||
} | ||
|
||
func TestToken_Unauthorized(t *testing.T) { | ||
r := chi.NewRouter() | ||
RegisterAuthHandler(r, Auth{}) | ||
|
||
req := httptest.NewRequest(http.MethodGet, "/token", nil) | ||
|
||
resp := httptest.NewRecorder() | ||
r.ServeHTTP(resp, req) | ||
|
||
assert(t, resp.Code, http.StatusUnauthorized) | ||
} | ||
|
||
func TestLogin(t *testing.T) { | ||
a := Auth{ | ||
GoogleOAuthConfig: &oauth2.Config{ | ||
ClientID: "client_id", | ||
ClientSecret: "client_secret", | ||
Endpoint: google.Endpoint, | ||
RedirectURL: "http://localhost:8080/callback", | ||
Scopes: []string{"https://www.googleapis.com/auth/userinfo.email"}, | ||
}, | ||
} | ||
|
||
r := chi.NewRouter() | ||
RegisterAuthHandler(r, a) | ||
|
||
req := httptest.NewRequest(http.MethodGet, "/", nil) | ||
|
||
resp := httptest.NewRecorder() | ||
r.ServeHTTP(resp, req) | ||
|
||
assert(t, resp.Code, http.StatusFound) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
package api | ||
|
||
import ( | ||
"github.com/go-chi/jwtauth/v5" | ||
"github.com/golang-jwt/jwt" | ||
"golang.org/x/oauth2" | ||
) | ||
|
||
// Auth have the configuration for Auth endpoints. | ||
type Auth struct { | ||
// Google OAuth2 | ||
ClientID string | ||
ClientSecret string | ||
RedirectURL string | ||
|
||
// Default domain | ||
Domain string | ||
// JWT secret key | ||
JWTSecretKey string | ||
// Google OAuth2 config struct | ||
GoogleOAuthConfig *oauth2.Config | ||
// Access type | ||
AccessType string // offline(for local) or online(for production) | ||
} | ||
|
||
// GenerateToken generates a JWT token for the given email. | ||
func (a *Auth) GenerateToken(email string) (string, error) { | ||
claims := jwt.MapClaims{ | ||
"email": email, | ||
} | ||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) | ||
return token.SignedString([]byte(a.JWTSecretKey)) | ||
} | ||
|
||
// JWTAuth returns a validated JWT token. | ||
func (a *Auth) JWTAuth() *jwtauth.JWTAuth { | ||
tokenAuth := jwtauth.New("HS256", []byte(a.JWTSecretKey), nil) | ||
return tokenAuth | ||
} |
Oops, something went wrong.