chore: update id type to int32

This commit is contained in:
Steven 2023-08-02 08:41:56 +08:00
parent c26834e9cd
commit d6dccb1f95
14 changed files with 61 additions and 50 deletions

View File

@ -1,11 +1,11 @@
package v1 package v1
type ActivityShorcutCreatePayload struct { type ActivityShorcutCreatePayload struct {
ShortcutID int `json:"shortcutId"` ShortcutID int32 `json:"shortcutId"`
} }
type ActivityShorcutViewPayload struct { type ActivityShorcutViewPayload struct {
ShortcutID int `json:"shortcutId"` ShortcutID int32 `json:"shortcutId"`
IP string `json:"ip"` IP string `json:"ip"`
Referer string `json:"referer"` Referer string `json:"referer"`
UserAgent string `json:"userAgent"` UserAgent string `json:"userAgent"`

View File

@ -3,7 +3,6 @@ package v1
import ( import (
"fmt" "fmt"
"net/http" "net/http"
"strconv"
"strings" "strings"
"time" "time"
@ -27,7 +26,7 @@ type claimsMessage struct {
} }
// GenerateAccessToken generates an access token for web. // GenerateAccessToken generates an access token for web.
func GenerateAccessToken(username string, userID int, secret string) (string, error) { func GenerateAccessToken(username string, userID int32, secret string) (string, error) {
expirationTime := time.Now().Add(auth.AccessTokenDuration) expirationTime := time.Now().Add(auth.AccessTokenDuration)
return generateToken(username, userID, auth.AccessTokenAudienceName, expirationTime, []byte(secret)) return generateToken(username, userID, auth.AccessTokenAudienceName, expirationTime, []byte(secret))
} }
@ -64,7 +63,7 @@ func setTokenCookie(c echo.Context, name, token string, expiration time.Time) {
} }
// generateToken generates a jwt token. // generateToken generates a jwt token.
func generateToken(username string, userID int, aud string, expirationTime time.Time, secret []byte) (string, error) { func generateToken(username string, userID int32, aud string, expirationTime time.Time, secret []byte) (string, error) {
// Create the JWT claims, which includes the username and expiry time. // Create the JWT claims, which includes the username and expiry time.
claims := &claimsMessage{ claims := &claimsMessage{
Name: username, Name: username,
@ -74,7 +73,7 @@ func generateToken(username string, userID int, aud string, expirationTime time.
ExpiresAt: jwt.NewNumericDate(expirationTime), ExpiresAt: jwt.NewNumericDate(expirationTime),
IssuedAt: jwt.NewNumericDate(time.Now()), IssuedAt: jwt.NewNumericDate(time.Now()),
Issuer: auth.Issuer, Issuer: auth.Issuer,
Subject: strconv.Itoa(userID), Subject: fmt.Sprint(userID),
}, },
} }
@ -172,9 +171,9 @@ func JWTMiddleware(server *APIV1Service, next echo.HandlerFunc, secret string) e
} }
// We either have a valid access token or we will attempt to generate new access token and refresh token // We either have a valid access token or we will attempt to generate new access token and refresh token
userID, err := strconv.Atoi(claims.Subject) userID, err := util.ConvertStringToInt32(claims.Subject)
if err != nil { if err != nil {
return echo.NewHTTPError(http.StatusUnauthorized, "Malformed ID in the token.") return echo.NewHTTPError(http.StatusUnauthorized, "Malformed ID in the token.").WithInternal(err)
} }
// Even if there is no error, we still need to make sure the user still exists. // Even if there is no error, we still need to make sure the user still exists.

View File

@ -31,7 +31,7 @@ func (s *APIV1Service) registerRedirectorRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("not found shortcut with name: %s", shortcutName)) return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("not found shortcut with name: %s", shortcutName))
} }
if shortcut.Visibility != store.VisibilityPublic { if shortcut.Visibility != store.VisibilityPublic {
userID, ok := c.Get(UserIDContextKey).(int) userID, ok := c.Get(UserIDContextKey).(int32)
if !ok { if !ok {
return echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized") return echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized")
} }

View File

@ -5,9 +5,9 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/http" "net/http"
"strconv"
"strings" "strings"
"github.com/boojack/slash/internal/util"
"github.com/boojack/slash/store" "github.com/boojack/slash/store"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/pkg/errors" "github.com/pkg/errors"
@ -36,10 +36,10 @@ type OpenGraphMetadata struct {
} }
type Shortcut struct { type Shortcut struct {
ID int `json:"id"` ID int32 `json:"id"`
// Standard fields // Standard fields
CreatorID int `json:"creatorId"` CreatorID int32 `json:"creatorId"`
Creator *User `json:"creator"` Creator *User `json:"creator"`
CreatedTs int64 `json:"createdTs"` CreatedTs int64 `json:"createdTs"`
UpdatedTs int64 `json:"updatedTs"` UpdatedTs int64 `json:"updatedTs"`
@ -80,7 +80,7 @@ type PatchShortcutRequest struct {
func (s *APIV1Service) registerShortcutRoutes(g *echo.Group) { func (s *APIV1Service) registerShortcutRoutes(g *echo.Group) {
g.POST("/shortcut", func(c echo.Context) error { g.POST("/shortcut", func(c echo.Context) error {
ctx := c.Request().Context() ctx := c.Request().Context()
userID, ok := c.Get(UserIDContextKey).(int) userID, ok := c.Get(UserIDContextKey).(int32)
if !ok { if !ok {
return echo.NewHTTPError(http.StatusUnauthorized, "missing user in session") return echo.NewHTTPError(http.StatusUnauthorized, "missing user in session")
} }
@ -120,11 +120,11 @@ func (s *APIV1Service) registerShortcutRoutes(g *echo.Group) {
g.PATCH("/shortcut/:shortcutId", func(c echo.Context) error { g.PATCH("/shortcut/:shortcutId", func(c echo.Context) error {
ctx := c.Request().Context() ctx := c.Request().Context()
shortcutID, err := strconv.Atoi(c.Param("shortcutId")) shortcutID, err := util.ConvertStringToInt32(c.Param("shortcutId"))
if err != nil { if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("shortcut ID is not a number: %s", c.Param("shortcutId"))).SetInternal(err) return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("shortcut ID is not a number: %s", c.Param("shortcutId"))).SetInternal(err)
} }
userID, ok := c.Get(UserIDContextKey).(int) userID, ok := c.Get(UserIDContextKey).(int32)
if !ok { if !ok {
return echo.NewHTTPError(http.StatusUnauthorized, "missing user in session") return echo.NewHTTPError(http.StatusUnauthorized, "missing user in session")
} }
@ -195,7 +195,7 @@ func (s *APIV1Service) registerShortcutRoutes(g *echo.Group) {
g.GET("/shortcut", func(c echo.Context) error { g.GET("/shortcut", func(c echo.Context) error {
ctx := c.Request().Context() ctx := c.Request().Context()
userID, ok := c.Get(UserIDContextKey).(int) userID, ok := c.Get(UserIDContextKey).(int32)
if !ok { if !ok {
return echo.NewHTTPError(http.StatusUnauthorized, "missing user in session") return echo.NewHTTPError(http.StatusUnauthorized, "missing user in session")
} }
@ -234,7 +234,7 @@ func (s *APIV1Service) registerShortcutRoutes(g *echo.Group) {
g.GET("/shortcut/:id", func(c echo.Context) error { g.GET("/shortcut/:id", func(c echo.Context) error {
ctx := c.Request().Context() ctx := c.Request().Context()
shortcutID, err := strconv.Atoi(c.Param("id")) shortcutID, err := util.ConvertStringToInt32(c.Param("id"))
if err != nil { if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("shortcut id is not a number: %s", c.Param("id"))).SetInternal(err) return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("shortcut id is not a number: %s", c.Param("id"))).SetInternal(err)
} }
@ -258,11 +258,11 @@ func (s *APIV1Service) registerShortcutRoutes(g *echo.Group) {
g.DELETE("/shortcut/:id", func(c echo.Context) error { g.DELETE("/shortcut/:id", func(c echo.Context) error {
ctx := c.Request().Context() ctx := c.Request().Context()
shortcutID, err := strconv.Atoi(c.Param("id")) shortcutID, err := util.ConvertStringToInt32(c.Param("id"))
if err != nil { if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("shortcut id is not a number: %s", c.Param("id"))).SetInternal(err) return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("shortcut id is not a number: %s", c.Param("id"))).SetInternal(err)
} }
userID, ok := c.Get(UserIDContextKey).(int) userID, ok := c.Get(UserIDContextKey).(int32)
if !ok { if !ok {
return echo.NewHTTPError(http.StatusUnauthorized, "missing user in session") return echo.NewHTTPError(http.StatusUnauthorized, "missing user in session")
} }

View File

@ -5,8 +5,8 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"net/mail" "net/mail"
"strconv"
"github.com/boojack/slash/internal/util"
"github.com/boojack/slash/store" "github.com/boojack/slash/store"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
@ -38,7 +38,7 @@ func (r Role) String() string {
} }
type User struct { type User struct {
ID int `json:"id"` ID int32 `json:"id"`
// Standard fields // Standard fields
CreatedTs int64 `json:"createdTs"` CreatedTs int64 `json:"createdTs"`
@ -83,7 +83,7 @@ type PatchUserRequest struct {
func (s *APIV1Service) registerUserRoutes(g *echo.Group) { func (s *APIV1Service) registerUserRoutes(g *echo.Group) {
g.POST("/user", func(c echo.Context) error { g.POST("/user", func(c echo.Context) error {
ctx := c.Request().Context() ctx := c.Request().Context()
userID, ok := c.Get(UserIDContextKey).(int) userID, ok := c.Get(UserIDContextKey).(int32)
if !ok { if !ok {
return echo.NewHTTPError(http.StatusUnauthorized, "Missing auth session") return echo.NewHTTPError(http.StatusUnauthorized, "Missing auth session")
} }
@ -144,7 +144,7 @@ func (s *APIV1Service) registerUserRoutes(g *echo.Group) {
// GET /api/user/me is used to check if the user is logged in. // GET /api/user/me is used to check if the user is logged in.
g.GET("/user/me", func(c echo.Context) error { g.GET("/user/me", func(c echo.Context) error {
ctx := c.Request().Context() ctx := c.Request().Context()
userID, ok := c.Get(UserIDContextKey).(int) userID, ok := c.Get(UserIDContextKey).(int32)
if !ok { if !ok {
return echo.NewHTTPError(http.StatusUnauthorized, "missing auth session") return echo.NewHTTPError(http.StatusUnauthorized, "missing auth session")
} }
@ -161,7 +161,7 @@ func (s *APIV1Service) registerUserRoutes(g *echo.Group) {
g.GET("/user/:id", func(c echo.Context) error { g.GET("/user/:id", func(c echo.Context) error {
ctx := c.Request().Context() ctx := c.Request().Context()
userID, err := strconv.Atoi(c.Param("id")) userID, err := util.ConvertStringToInt32(c.Param("id"))
if err != nil { if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("user id is not a number: %s", c.Param("id"))).SetInternal(err) return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("user id is not a number: %s", c.Param("id"))).SetInternal(err)
} }
@ -178,11 +178,11 @@ func (s *APIV1Service) registerUserRoutes(g *echo.Group) {
g.PATCH("/user/:id", func(c echo.Context) error { g.PATCH("/user/:id", func(c echo.Context) error {
ctx := c.Request().Context() ctx := c.Request().Context()
userID, err := strconv.Atoi(c.Param("id")) userID, err := util.ConvertStringToInt32(c.Param("id"))
if err != nil { if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("user id is not a number: %s", c.Param("id"))).SetInternal(err) return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("user id is not a number: %s", c.Param("id"))).SetInternal(err)
} }
currentUserID, ok := c.Get(UserIDContextKey).(int) currentUserID, ok := c.Get(UserIDContextKey).(int32)
if !ok { if !ok {
return echo.NewHTTPError(http.StatusUnauthorized, "missing user in session") return echo.NewHTTPError(http.StatusUnauthorized, "missing user in session")
} }
@ -254,7 +254,7 @@ func (s *APIV1Service) registerUserRoutes(g *echo.Group) {
g.DELETE("/user/:id", func(c echo.Context) error { g.DELETE("/user/:id", func(c echo.Context) error {
ctx := c.Request().Context() ctx := c.Request().Context()
currentUserID, ok := c.Get(UserIDContextKey).(int) currentUserID, ok := c.Get(UserIDContextKey).(int32)
if !ok { if !ok {
return echo.NewHTTPError(http.StatusUnauthorized, "missing user in session") return echo.NewHTTPError(http.StatusUnauthorized, "missing user in session")
} }
@ -271,7 +271,7 @@ func (s *APIV1Service) registerUserRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusForbidden, "access forbidden for current session user").SetInternal(err) return echo.NewHTTPError(http.StatusForbidden, "access forbidden for current session user").SetInternal(err)
} }
userID, err := strconv.Atoi(c.Param("id")) userID, err := util.ConvertStringToInt32(c.Param("id"))
if err != nil { if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("user id is not a number: %s", c.Param("id"))).SetInternal(err) return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("user id is not a number: %s", c.Param("id"))).SetInternal(err)
} }

View File

@ -62,7 +62,7 @@ func (s *APIV1Service) registerWorkspaceRoutes(g *echo.Group) {
g.POST("/workspace/setting", func(c echo.Context) error { g.POST("/workspace/setting", func(c echo.Context) error {
ctx := c.Request().Context() ctx := c.Request().Context()
userID, ok := c.Get(UserIDContextKey).(int) userID, ok := c.Get(UserIDContextKey).(int32)
if !ok { if !ok {
return echo.NewHTTPError(http.StatusUnauthorized, "missing user in session") return echo.NewHTTPError(http.StatusUnauthorized, "missing user in session")
} }
@ -97,7 +97,7 @@ func (s *APIV1Service) registerWorkspaceRoutes(g *echo.Group) {
g.GET("/workspace/setting", func(c echo.Context) error { g.GET("/workspace/setting", func(c echo.Context) error {
ctx := c.Request().Context() ctx := c.Request().Context()
userID, ok := c.Get(UserIDContextKey).(int) userID, ok := c.Get(UserIDContextKey).(int32)
if !ok { if !ok {
return echo.NewHTTPError(http.StatusUnauthorized, "missing user in session") return echo.NewHTTPError(http.StatusUnauthorized, "missing user in session")
} }

View File

@ -8,6 +8,7 @@ import (
"time" "time"
"github.com/boojack/slash/api/auth" "github.com/boojack/slash/api/auth"
"github.com/boojack/slash/internal/util"
"github.com/boojack/slash/store" "github.com/boojack/slash/store"
"github.com/golang-jwt/jwt/v4" "github.com/golang-jwt/jwt/v4"
"github.com/pkg/errors" "github.com/pkg/errors"
@ -76,7 +77,7 @@ func (in *GRPCAuthInterceptor) AuthenticationInterceptor(ctx context.Context, re
return handler(childCtx, request) return handler(childCtx, request)
} }
func (in *GRPCAuthInterceptor) authenticate(ctx context.Context, accessTokenStr string) (int, error) { func (in *GRPCAuthInterceptor) authenticate(ctx context.Context, accessTokenStr string) (int32, error) {
if accessTokenStr == "" { if accessTokenStr == "" {
return 0, status.Errorf(codes.Unauthenticated, "access token not found") return 0, status.Errorf(codes.Unauthenticated, "access token not found")
} }
@ -103,7 +104,7 @@ func (in *GRPCAuthInterceptor) authenticate(ctx context.Context, accessTokenStr
) )
} }
userID, err := strconv.Atoi(claims.Subject) userID, err := util.ConvertStringToInt32(claims.Subject)
if err != nil { if err != nil {
return 0, status.Errorf(codes.Unauthenticated, "malformed ID %q in the access token", claims.Subject) return 0, status.Errorf(codes.Unauthenticated, "malformed ID %q in the access token", claims.Subject)
} }

View File

@ -23,9 +23,8 @@ func NewUserService(store *store.Store) *UserService {
} }
func (s *UserService) GetUser(ctx context.Context, request *apiv2pb.GetUserRequest) (*apiv2pb.GetUserResponse, error) { func (s *UserService) GetUser(ctx context.Context, request *apiv2pb.GetUserRequest) (*apiv2pb.GetUserResponse, error) {
id := int(request.Id)
user, err := s.Store.GetUser(ctx, &store.FindUser{ user, err := s.Store.GetUser(ctx, &store.FindUser{
ID: &id, ID: &request.Id,
}) })
if err != nil { if err != nil {
return nil, status.Errorf(codes.Internal, "failed to list tags: %v", err) return nil, status.Errorf(codes.Internal, "failed to list tags: %v", err)

View File

@ -1,6 +1,18 @@
package util package util
import "strings" import (
"strconv"
"strings"
)
// ConvertStringToInt32 converts a string to int32.
func ConvertStringToInt32(src string) (int32, error) {
i, err := strconv.Atoi(src)
if err != nil {
return 0, err
}
return int32(i), nil
}
// HasPrefixes returns true if the string s has any of the given prefixes. // HasPrefixes returns true if the string s has any of the given prefixes.
func HasPrefixes(src string, prefixes ...string) bool { func HasPrefixes(src string, prefixes ...string) bool {

View File

@ -48,8 +48,8 @@ func (l ActivityLevel) String() string {
} }
type Activity struct { type Activity struct {
ID int ID int32
CreatorID int CreatorID int32
CreatedTs int64 CreatedTs int64
Type ActivityType Type ActivityType
Level ActivityLevel Level ActivityLevel

View File

@ -2,6 +2,6 @@ package store
import "fmt" import "fmt"
func getUserSettingCacheKey(userID int, key string) string { func getUserSettingCacheKey(userID int32, key string) string {
return fmt.Sprintf("%d-%s", userID, key) return fmt.Sprintf("%d-%s", userID, key)
} }

View File

@ -39,10 +39,10 @@ type OpenGraphMetadata struct {
} }
type Shortcut struct { type Shortcut struct {
ID int ID int32
// Standard fields // Standard fields
CreatorID int CreatorID int32
CreatedTs int64 CreatedTs int64
UpdatedTs int64 UpdatedTs int64
RowStatus RowStatus RowStatus RowStatus
@ -58,7 +58,7 @@ type Shortcut struct {
} }
type UpdateShortcut struct { type UpdateShortcut struct {
ID int ID int32
RowStatus *RowStatus RowStatus *RowStatus
Name *string Name *string
@ -71,8 +71,8 @@ type UpdateShortcut struct {
} }
type FindShortcut struct { type FindShortcut struct {
ID *int ID *int32
CreatorID *int CreatorID *int32
RowStatus *RowStatus RowStatus *RowStatus
Name *string Name *string
VisibilityList []Visibility VisibilityList []Visibility
@ -80,7 +80,7 @@ type FindShortcut struct {
} }
type DeleteShortcut struct { type DeleteShortcut struct {
ID int ID int32
} }
func (s *Store) CreateShortcut(ctx context.Context, create *Shortcut) (*Shortcut, error) { func (s *Store) CreateShortcut(ctx context.Context, create *Shortcut) (*Shortcut, error) {

View File

@ -17,7 +17,7 @@ const (
) )
type User struct { type User struct {
ID int ID int32
// Standard fields // Standard fields
CreatedTs int64 CreatedTs int64
@ -32,7 +32,7 @@ type User struct {
} }
type UpdateUser struct { type UpdateUser struct {
ID int ID int32
RowStatus *RowStatus RowStatus *RowStatus
Email *string Email *string
@ -42,7 +42,7 @@ type UpdateUser struct {
} }
type FindUser struct { type FindUser struct {
ID *int ID *int32
RowStatus *RowStatus RowStatus *RowStatus
Email *string Email *string
Nickname *string Nickname *string
@ -50,7 +50,7 @@ type FindUser struct {
} }
type DeleteUser struct { type DeleteUser struct {
ID int ID int32
} }
func (s *Store) CreateUser(ctx context.Context, create *User) (*User, error) { func (s *Store) CreateUser(ctx context.Context, create *User) (*User, error) {

View File

@ -7,13 +7,13 @@ import (
) )
type UserSetting struct { type UserSetting struct {
UserID int UserID int32
Key string Key string
Value string Value string
} }
type FindUserSetting struct { type FindUserSetting struct {
UserID *int UserID *int32
Key string Key string
} }