diff --git a/auth/middleware.go b/auth/middleware.go index ea470df..351189a 100644 --- a/auth/middleware.go +++ b/auth/middleware.go @@ -19,6 +19,7 @@ const ( type userInfo struct { Username string Password string + UserID int64 } func (a *authorizer) Interceptor( @@ -59,12 +60,12 @@ func (a *authorizer) authorize(ctx context.Context) (context.Context, error) { token := authHeader[0] - username, password, err := ParseToken(token, []byte(a.key)) + username, password, userID, err := ParseToken(token, []byte(a.key)) if err != nil { return ctx, status.Errorf(codes.Unauthenticated, err.Error()) } - return context.WithValue(ctx, UserKey, userInfo{Username: username, Password: password}), nil + return context.WithValue(ctx, UserKey, userInfo{Username: username, Password: password, UserID: userID}), nil } func GetUserInfo(ctx context.Context) (*userInfo, error) { diff --git a/auth/parse_token.go b/auth/parse_token.go index c5fb735..21f01e0 100644 --- a/auth/parse_token.go +++ b/auth/parse_token.go @@ -6,7 +6,7 @@ import ( "github.com/dgrijalva/jwt-go/v4" ) -func ParseToken(accessToken string, signingKey []byte) (string, string, error) { +func ParseToken(accessToken string, signingKey []byte) (string, string, int64, error) { token, err := jwt.ParseWithClaims(accessToken, &Claims{}, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) @@ -15,12 +15,12 @@ func ParseToken(accessToken string, signingKey []byte) (string, string, error) { }) if err != nil { - return "", "", err + return "", "", 0, err } if claims, ok := token.Claims.(*Claims); ok && token.Valid { - return claims.Username, claims.Password, nil + return claims.Username, claims.Password, claims.UserID, nil } - return "", "", ErrInvalidAccessToken + return "", "", 0, ErrInvalidAccessToken } diff --git a/auth/sign_in.go b/auth/sign_in.go index 4c2ab0a..f1c993c 100644 --- a/auth/sign_in.go +++ b/auth/sign_in.go @@ -12,6 +12,7 @@ type Claims struct { jwt.StandardClaims Username string `json:"username"` Password string `json:"password"` + UserID int64 `json:"user_id"` } type authorizer struct { @@ -23,7 +24,7 @@ func NewAuthorizer(key string, expireDuration time.Duration) *authorizer { return &authorizer{key: key, expireDuration: expireDuration} } -func (a *authorizer) GetToken(login, password, salt string) (string, error) { +func (a *authorizer) GetToken(login, password, salt string, userID int64) (string, error) { token := jwt.NewWithClaims(jwt.SigningMethodHS256, &Claims{ StandardClaims: jwt.StandardClaims{ ExpiresAt: jwt.At(time.Now().Add(a.expireDuration)), @@ -31,6 +32,7 @@ func (a *authorizer) GetToken(login, password, salt string) (string, error) { }, Username: login, Password: HashPassword(password, salt), + UserID: userID, }) return token.SignedString([]byte(a.key))