Squashed commit of the following:
commitd2ec8c0f07Author: mario <dev.mario@sismedika@gmail.com> Date: Thu May 15 15:42:33 2025 +0700 add: db tx commit and rollback implementation commit264435f67eAuthor: mario <dev.mario@sismedika@gmail.com> Date: Thu May 15 14:34:20 2025 +0700 fix: shortlink generation logic update/create commit047ab1937aAuthor: mario <dev.mario@sismedika@gmail.com> Date: Thu May 15 11:06:04 2025 +0700 fix: if multiple studies patient, show first study by default commitc13f834b92Author: mario <dev.mario@sismedika@gmail.com> Date: Thu May 15 09:46:32 2025 +0700 add: register and login with DB query AND some struct type correction commitdd4451c2a8Author: mario <dev.mario@sismedika@gmail.com> Date: Wed May 14 10:23:33 2025 +0700 new file structure & koneksi ke DB commit8289881df3Author: mario <dev.mario@sismedika@gmail.com> Date: Tue May 13 16:49:07 2025 +0700 edit: rm debug route commitdd784da232Author: mario <dev.mario@sismedika@gmail.com> Date: Tue May 13 15:44:11 2025 +0700 add: implement shortlink commit2687a761ccAuthor: mario <dev.mario@sismedika@gmail.com> Date: Tue May 13 11:47:19 2025 +0700 add new dummy doctor user commiteb67eaca46Author: mario <dev.mario@sismedika@gmail.com> Date: Tue May 13 11:46:28 2025 +0700 add: ref_doctor studylist filter commit0d4825d152Author: mario <dev.mario@sismedika@gmail.com> Date: Tue May 13 10:07:16 2025 +0700 edit study_iuids & accNum in patient jwt to array commit2d1f135fdaAuthor: mario <dev.mario@sismedika@gmail.com> Date: Tue May 13 09:52:45 2025 +0700 patient see their multiple studies commit13bb380f51Author: mario <dev.mario@sismedika@gmail.com> Date: Fri May 9 10:13:16 2025 +0700 add: cors handler route and readme commit6c9ab574ceAuthor: mario <dev.mario@sismedika@gmail.com> Date: Mon May 5 11:50:36 2025 +0700 add: login & token validation tapi belum connect ke DB commit297c9a6a01Author: mario <dev.mario@sismedika@gmail.com> Date: Mon Apr 28 15:37:02 2025 +0700 add readme.md commit9b8e0260f3Author: mario <dev.mario@sismedika@gmail.com> Date: Mon Apr 7 15:46:07 2025 +0700 connected-to-google commitf340bc5916Author: mario <dev.mario@sismedika.com> Date: Mon Apr 7 11:14:18 2025 +0700 init
This commit is contained in:
68
internal/auth/google.go
Normal file
68
internal/auth/google.go
Normal file
@@ -0,0 +1,68 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"golang.org/x/oauth2"
|
||||
"golang.org/x/oauth2/google"
|
||||
"google.golang.org/api/healthcare/v1"
|
||||
"google.golang.org/api/option"
|
||||
)
|
||||
|
||||
// GoogleClient handles authentication with Google APIs
|
||||
type GoogleClient struct {
|
||||
credentialsPath string
|
||||
tokenSource oauth2.TokenSource
|
||||
}
|
||||
|
||||
// NewGoogleClient creates a new Google authentication client
|
||||
func NewGoogleClient(credentialsPath string) (*GoogleClient, error) {
|
||||
client := &GoogleClient{
|
||||
credentialsPath: credentialsPath,
|
||||
}
|
||||
|
||||
// Initialize on creation to validate credentials
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Try reading the credentials file
|
||||
credBytes, err := os.ReadFile(credentialsPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read credentials file: %w", err)
|
||||
}
|
||||
|
||||
// Create credentials from the JSON key file
|
||||
creds, err := google.CredentialsFromJSON(ctx, credBytes, healthcare.CloudPlatformScope)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to initialize Google client: %w", err)
|
||||
}
|
||||
|
||||
client.tokenSource = creds.TokenSource
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// GetAccessToken returns a valid access token for Google APIs
|
||||
func (c *GoogleClient) GetAccessToken() (string, error) {
|
||||
_, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
token, err := c.tokenSource.Token()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to get access token: %w", err)
|
||||
}
|
||||
|
||||
return token.AccessToken, nil
|
||||
}
|
||||
|
||||
// GetHealthcareClient returns a configured Healthcare API client
|
||||
func (c *GoogleClient) GetHealthcareClient(ctx context.Context) (*healthcare.Service, error) {
|
||||
opts := []option.ClientOption{
|
||||
option.WithCredentialsFile(c.credentialsPath),
|
||||
option.WithScopes(healthcare.CloudPlatformScope),
|
||||
}
|
||||
|
||||
return healthcare.NewService(ctx, opts...)
|
||||
}
|
||||
182
internal/auth/jwt.go
Normal file
182
internal/auth/jwt.go
Normal file
@@ -0,0 +1,182 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidToken = errors.New("invalid token")
|
||||
ErrExpiredToken = errors.New("token has expired")
|
||||
)
|
||||
|
||||
// JWTManager handles JWT token operations
|
||||
type JWTManager struct {
|
||||
secretKey string
|
||||
accessExpiry time.Duration
|
||||
refreshExpiry time.Duration
|
||||
}
|
||||
|
||||
// NewJWTManager creates a new JWT manager
|
||||
func NewJWTManager(secretKey string, accessExpiry, refreshExpiry time.Duration) *JWTManager {
|
||||
return &JWTManager{
|
||||
secretKey: secretKey,
|
||||
accessExpiry: accessExpiry,
|
||||
refreshExpiry: refreshExpiry,
|
||||
}
|
||||
}
|
||||
|
||||
// CustomClaims contains the claims we want in our tokens
|
||||
type CustomClaims struct {
|
||||
UserID string `json:"user_id"`
|
||||
Email string `json:"email"`
|
||||
Role string `json:"role"`
|
||||
UserName string `json:"user_name"`
|
||||
TokenType string `json:"token_type"` // access or refresh
|
||||
|
||||
// Patient-specific fields
|
||||
PatientID string `json:"patient_id,omitempty"`
|
||||
PatientName string `json:"patient_name,omitempty"`
|
||||
StudyIUIDs []string `json:"study_iuids,omitempty"`
|
||||
AccessionNumbers []string `json:"accession_numbers,omitempty"`
|
||||
|
||||
// Navigation and permissions
|
||||
HomeURL string `json:"home_url,omitempty"`
|
||||
StudyList string `json:"study_list,omitempty"` // enabled or disabled
|
||||
FilterURL string `json:"filter_url,omitempty"` // for ref_doctor filtering
|
||||
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
// GenerateAccessToken creates a new access token with role-specific claims
|
||||
func (m *JWTManager) GenerateAccessToken(userID, email, role, userName string, additionalClaims map[string]interface{}) (string, error) {
|
||||
claims := CustomClaims{
|
||||
UserID: userID,
|
||||
Email: email,
|
||||
Role: role,
|
||||
UserName: userName,
|
||||
TokenType: "access",
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(m.accessExpiry)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
}
|
||||
|
||||
// Add role-specific additional claims
|
||||
if additionalClaims != nil {
|
||||
// Handle string claims
|
||||
if val, ok := additionalClaims["patient_id"].(string); ok {
|
||||
claims.PatientID = val
|
||||
}
|
||||
if val, ok := additionalClaims["patient_name"].(string); ok {
|
||||
claims.PatientName = val
|
||||
}
|
||||
if val, ok := additionalClaims["home_url"].(string); ok {
|
||||
claims.HomeURL = val
|
||||
}
|
||||
if val, ok := additionalClaims["study_list"].(string); ok {
|
||||
claims.StudyList = val
|
||||
}
|
||||
if val, ok := additionalClaims["filter_url"].(string); ok {
|
||||
claims.FilterURL = val
|
||||
}
|
||||
|
||||
// Handle array claims
|
||||
if val, ok := additionalClaims["study_iuids"].([]string); ok {
|
||||
claims.StudyIUIDs = val
|
||||
}
|
||||
if val, ok := additionalClaims["accession_numbers"].([]string); ok {
|
||||
claims.AccessionNumbers = val
|
||||
}
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString([]byte(m.secretKey))
|
||||
}
|
||||
|
||||
// GenerateRefreshToken creates a new refresh token with the same claims as access token
|
||||
func (m *JWTManager) GenerateRefreshToken(userID, email, role, userName string, additionalClaims map[string]interface{}) (string, error) {
|
||||
claims := CustomClaims{
|
||||
UserID: userID,
|
||||
Email: email,
|
||||
Role: role,
|
||||
UserName: userName,
|
||||
TokenType: "refresh",
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(m.refreshExpiry)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
}
|
||||
|
||||
// Add role-specific additional claims
|
||||
if additionalClaims != nil {
|
||||
// Handle string claims
|
||||
if val, ok := additionalClaims["patient_id"].(string); ok {
|
||||
claims.PatientID = val
|
||||
}
|
||||
if val, ok := additionalClaims["patient_name"].(string); ok {
|
||||
claims.PatientName = val
|
||||
}
|
||||
if val, ok := additionalClaims["home_url"].(string); ok {
|
||||
claims.HomeURL = val
|
||||
}
|
||||
if val, ok := additionalClaims["study_list"].(string); ok {
|
||||
claims.StudyList = val
|
||||
}
|
||||
if val, ok := additionalClaims["filter_url"].(string); ok {
|
||||
claims.FilterURL = val
|
||||
}
|
||||
|
||||
// Handle array claims
|
||||
if val, ok := additionalClaims["study_iuids"].([]string); ok {
|
||||
claims.StudyIUIDs = val
|
||||
}
|
||||
if val, ok := additionalClaims["accession_numbers"].([]string); ok {
|
||||
claims.AccessionNumbers = val
|
||||
}
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString([]byte(m.secretKey))
|
||||
}
|
||||
|
||||
// ValidateToken validates a token and returns the claims
|
||||
func (m *JWTManager) ValidateToken(tokenString string) (*CustomClaims, error) {
|
||||
token, err := jwt.ParseWithClaims(
|
||||
tokenString,
|
||||
&CustomClaims{},
|
||||
func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return []byte(m.secretKey), nil
|
||||
},
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, jwt.ErrTokenExpired) {
|
||||
return nil, ErrExpiredToken
|
||||
}
|
||||
return nil, ErrInvalidToken
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(*CustomClaims)
|
||||
if !ok || !token.Valid {
|
||||
return nil, ErrInvalidToken
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
// GetAccessExpiry returns the configured access token expiry duration
|
||||
func (m *JWTManager) GetAccessExpiry() time.Duration {
|
||||
return m.accessExpiry
|
||||
}
|
||||
|
||||
// GetRefreshExpiry returns the configured refresh token expiry duration
|
||||
func (m *JWTManager) GetRefreshExpiry() time.Duration {
|
||||
return m.refreshExpiry
|
||||
}
|
||||
Reference in New Issue
Block a user