hackathon/api/api.go

85 lines
2.3 KiB
Go

package api
import (
"context"
"time"
codequestpb "github.com/hhhapz/codequest/api/v1"
"github.com/hhhapz/codequest/models"
"github.com/hhhapz/codequest/question"
"golang.org/x/oauth2"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
// 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(string) string
Validate(context.Context, string, string) (*oauth2.Token, string, error)
}
type UserStore interface {
ConsumeToken(context.Context, *oauth2.Token) (*models.Token, error)
CreateToken(context.Context, *models.User) (*models.Token, error)
RevokeToken(context.Context, string) error
RevokeUserTokens(context.Context, *models.User) (int64, error)
User(context.Context, string) (*models.User, error)
UserPoints(context.Context, *models.User) (int, error)
Users(context.Context) ([]*models.User, error)
UserByToken(context.Context, string) (*models.User, error)
UpdateUser(context.Context, *models.User) error
DeleteUser(context.Context, *models.User) error
}
type QuestStore interface {
Questions(context.Context, *models.User) ([]*question.Data, error)
Question(context.Context, *models.User, string) (*question.Data, error)
Submissions(context.Context, *models.User, string, question.Part) (bool, int, error)
AddSubmission(context.Context, *models.QuestionAttempt) error
Leaderboard(context.Context) ([]*models.LeaderboardEntry, error)
}
type CooldownStore interface {
NewAttempt(userID string, questionID string, attempts int)
Check(userID string, questionID string) time.Duration
}
type Server struct {
*AuthService
*UserService
*QuestService
}
func NewServer(os OAuthStore, us UserStore, qs QuestStore, cs CooldownStore) (*grpc.Server, error) {
s := &Server{
AuthService: &AuthService{
oauthStore: os,
userStore: us,
},
UserService: &UserService{
userStore: us,
},
QuestService: &QuestService{
userStore: us,
questStore: qs,
cooldownStore: cs,
},
}
srv := grpc.NewServer(
grpc.UnaryInterceptor(AuthInterceptor(s.AuthService.defaultAuthFunc)),
)
reflection.Register(srv)
codequestpb.RegisterAuthServiceServer(srv, s.AuthService)
codequestpb.RegisterUserServiceServer(srv, s.UserService)
codequestpb.RegisterQuestServiceServer(srv, s.QuestService)
return srv, nil
}