hackathon/api/api.go

74 lines
1.8 KiB
Go

2021-09-30 10:32:18 +07:00
package api
import (
"context"
2021-12-19 15:30:21 +07:00
codequestpb "github.com/hhhapz/codequest/api/v1"
"github.com/hhhapz/codequest/models"
2021-09-30 10:32:18 +07:00
"golang.org/x/oauth2"
2021-12-19 15:30:21 +07:00
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/reflection"
2021-09-30 10:32:18 +07:00
)
// inProd tells the server whether it is in prod.
// It should be set using ldflags on build time.
var inProd bool
type OAuthStore interface {
Create(callback string) (code string)
Validate(code string) (string, bool)
Exchange(ctx context.Context, code string) (*oauth2.Token, error)
}
type UserStore interface {
2021-12-19 15:30:21 +07:00
ConsumeToken(ctx context.Context, token *oauth2.Token) (*models.Token, bool, error)
2021-09-30 10:32:18 +07:00
CreateToken(ctx context.Context, user *models.User) (*models.Token, error)
RevokeToken(ctx context.Context, token string) error
RevokeUserTokens(ctx context.Context, user *models.User) (int64, error)
User(ctx context.Context, email string) (*models.User, error)
Users(ctx context.Context) ([]*models.User, error)
UserByToken(ctx context.Context, token string) (*models.User, error)
UpdateUser(ctx context.Context, user *models.User) error
2021-12-19 15:30:21 +07:00
DeleteUser(ctx context.Context, user *models.User) error
2021-09-30 10:32:18 +07:00
}
2021-12-19 15:30:21 +07:00
type Server struct {
*AuthService
*UserService
}
2021-09-30 10:32:18 +07:00
2021-12-19 15:30:21 +07:00
func NewServer(os OAuthStore, us UserStore) (*grpc.Server, error) {
s := &Server{
2021-09-30 10:32:18 +07:00
AuthService: &AuthService{
2021-12-19 15:30:21 +07:00
oauthStore: os,
userStore: us,
2021-09-30 10:32:18 +07:00
},
UserService: &UserService{
2021-12-19 15:30:21 +07:00
userStore: us,
2021-09-30 10:32:18 +07:00
},
}
2021-12-19 15:30:21 +07:00
srv := grpc.NewServer(
grpc.UnaryInterceptor(AuthInterceptor(s.AuthService.defaultAuthFunc)),
)
reflection.Register(srv)
codequestpb.RegisterAuthServiceServer(srv, s.AuthService)
codequestpb.RegisterUserServiceServer(srv, s.UserService)
return srv, nil
2021-09-30 10:32:18 +07:00
}
2021-12-19 15:30:21 +07:00
// List of commonly used error values
var (
ErrInvalidArgument = grpc.Errorf(
codes.InvalidArgument,
"Invalid argument",
)
)
2021-09-30 10:32:18 +07:00
2021-12-19 15:30:21 +07:00
func err() {
2021-09-30 10:32:18 +07:00
}