Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat: implement auth service (#4036)

Danny Xub6da385d1265
diff --git a/frontend/src/types/proto/v1/auth_service.ts b/frontend/src/types/proto/v1/auth_service.ts
new file mode 100644
index 0000000000..918d163f50
--- /dev/null
+++ b/frontend/src/types/proto/v1/auth_service.ts
@@ -0,0 +1,156 @@
+/* eslint-disable */
+import _m0 from "protobufjs/minimal";
+
+export const protobufPackage = "bytebase.v1";
+
+export interface LoginRequest {
+ email: string;
+ password: string;
+}
+
+export interface LoginResponse {
+ token: string;
+}
+
+function createBaseLoginRequest(): LoginRequest {
+ return { email: "", password: "" };
+}
+
+export const LoginRequest = {
+ encode(message: LoginRequest, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
+ if (message.email !== "") {
+ writer.uint32(10).string(message.email);
+ }
+ if (message.password !== "") {
+ writer.uint32(18).string(message.password);
+ }
+ return writer;
+ },
+
+ decode(input: _m0.Reader | Uint8Array, length?: number): LoginRequest {
+ const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
+ let end = length === undefined ? reader.len : reader.pos + length;
+ const message = createBaseLoginRequest();
+ while (reader.pos < end) {
+ const tag = reader.uint32();
+ switch (tag >>> 3) {
+ case 1:
+ message.email = reader.string();
+ break;
+ case 2:
+ message.password = reader.string();
+ break;
+ default:
+ reader.skipType(tag & 7);
+ break;
+ }
+ }
+ return message;
+ },
+
+ fromJSON(object: any): LoginRequest {
+ return {
+ email: isSet(object.email) ? String(object.email) : "",
+ password: isSet(object.password) ? String(object.password) : "",
+ };
+ },
+
+ toJSON(message: LoginRequest): unknown {
+ const obj: any = {};
+ message.email !== undefined && (obj.email = message.email);
+ message.password !== undefined && (obj.password = message.password);
+ return obj;
+ },
+
+ fromPartial<I extends Exact<DeepPartial<LoginRequest>, I>>(object: I): LoginRequest {
+ const message = createBaseLoginRequest();
+ message.email = object.email ?? "";
+ message.password = object.password ?? "";
+ return message;
+ },
+};
+
+function createBaseLoginResponse(): LoginResponse {
+ return { token: "" };
+}
+
+export const LoginResponse = {
+ encode(message: LoginResponse, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
+ if (message.token !== "") {
+ writer.uint32(10).string(message.token);
+ }
+ return writer;
+ },
+
+ decode(input: _m0.Reader | Uint8Array, length?: number): LoginResponse {
+ const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
+ let end = length === undefined ? reader.len : reader.pos + length;
+ const message = createBaseLoginResponse();
+ while (reader.pos < end) {
+ const tag = reader.uint32();
+ switch (tag >>> 3) {
+ case 1:
+ message.token = reader.string();
+ break;
+ default:
+ reader.skipType(tag & 7);
+ break;
+ }
+ }
+ return message;
+ },
+
+ fromJSON(object: any): LoginResponse {
+ return { token: isSet(object.token) ? String(object.token) : "" };
+ },
+
+ toJSON(message: LoginResponse): unknown {
+ const obj: any = {};
+ message.token !== undefined && (obj.token = message.token);
+ return obj;
+ },
+
+ fromPartial<I extends Exact<DeepPartial<LoginResponse>, I>>(object: I): LoginResponse {
+ const message = createBaseLoginResponse();
+ message.token = object.token ?? "";
+ return message;
+ },
+};
+
+export interface AuthService {
+ Login(request: LoginRequest): Promise<LoginResponse>;
+}
+
+export class AuthServiceClientImpl implements AuthService {
+ private readonly rpc: Rpc;
+ private readonly service: string;
+ constructor(rpc: Rpc, opts?: { service?: string }) {
+ this.service = opts?.service || "bytebase.v1.AuthService";
+ this.rpc = rpc;
+ this.Login = this.Login.bind(this);
+ }
+ Login(request: LoginRequest): Promise<LoginResponse> {
+ const data = LoginRequest.encode(request).finish();
+ const promise = this.rpc.request(this.service, "Login", data);
+ return promise.then((data) => LoginResponse.decode(new _m0.Reader(data)));
+ }
+}
+
+interface Rpc {
+ request(service: string, method: string, data: Uint8Array): Promise<Uint8Array>;
+}
+
+type Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;
+
+export type DeepPartial<T> = T extends Builtin ? T
+ : T extends Array<infer U> ? Array<DeepPartial<U>> : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>
+ : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }
+ : Partial<T>;
+
+type KeysOfUnion<T> = T extends T ? keyof T : never;
+export type Exact<P, I extends P> = P extends Builtin ? P
+ : P & { [K in keyof P]: Exact<P[K], I[K]> } & { [K in Exclude<keyof I, KeysOfUnion<P>>]: never };
+
+function isSet(value: any): boolean {
+ return value !== null && value !== undefined;
+}
diff --git a/proto/generated-go/v1/auth_service.pb.go b/proto/generated-go/v1/auth_service.pb.go
new file mode 100644
index 0000000000..40c242d56e
--- /dev/null
+++ b/proto/generated-go/v1/auth_service.pb.go
@@ -0,0 +1,226 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// versions:
+// protoc-gen-go v1.28.1
+// protoc (unknown)
+// source: v1/auth_service.proto
+
+package v1
+
+import (
+ _ "google.golang.org/genproto/googleapis/api/annotations"
+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"
+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"
+ reflect "reflect"
+ sync "sync"
+)
+
+const (
+ // Verify that this generated code is sufficiently up-to-date.
+ _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
+ // Verify that runtime/protoimpl is sufficiently up-to-date.
+ _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
+)
+
+type LoginRequest struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+
+ Email string `protobuf:"bytes,1,opt,name=email,proto3" json:"email,omitempty"`
+ Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"`
+}
+
+func (x *LoginRequest) Reset() {
+ *x = LoginRequest{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_v1_auth_service_proto_msgTypes[0]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *LoginRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*LoginRequest) ProtoMessage() {}
+
+func (x *LoginRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_v1_auth_service_proto_msgTypes[0]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use LoginRequest.ProtoReflect.Descriptor instead.
+func (*LoginRequest) Descriptor() ([]byte, []int) {
+ return file_v1_auth_service_proto_rawDescGZIP(), []int{0}
+}
+
+func (x *LoginRequest) GetEmail() string {
+ if x != nil {
+ return x.Email
+ }
+ return ""
+}
+
+func (x *LoginRequest) GetPassword() string {
+ if x != nil {
+ return x.Password
+ }
+ return ""
+}
+
+type LoginResponse struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+
+ Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"`
+}
+
+func (x *LoginResponse) Reset() {
+ *x = LoginResponse{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_v1_auth_service_proto_msgTypes[1]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *LoginResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*LoginResponse) ProtoMessage() {}
+
+func (x *LoginResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_v1_auth_service_proto_msgTypes[1]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use LoginResponse.ProtoReflect.Descriptor instead.
+func (*LoginResponse) Descriptor() ([]byte, []int) {
+ return file_v1_auth_service_proto_rawDescGZIP(), []int{1}
+}
+
+func (x *LoginResponse) GetToken() string {
+ if x != nil {
+ return x.Token
+ }
+ return ""
+}
+
+var File_v1_auth_service_proto protoreflect.FileDescriptor
+
+var file_v1_auth_service_proto_rawDesc = []byte{
+ 0x0a, 0x15, 0x76, 0x31, 0x2f, 0x61, 0x75, 0x74, 0x68, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63,
+ 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0b, 0x62, 0x79, 0x74, 0x65, 0x62, 0x61, 0x73,
+ 0x65, 0x2e, 0x76, 0x31, 0x1a, 0x1c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69,
+ 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f,
+ 0x74, 0x6f, 0x22, 0x40, 0x0a, 0x0c, 0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65,
+ 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28,
+ 0x09, 0x52, 0x05, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x12, 0x1a, 0x0a, 0x08, 0x70, 0x61, 0x73, 0x73,
+ 0x77, 0x6f, 0x72, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x70, 0x61, 0x73, 0x73,
+ 0x77, 0x6f, 0x72, 0x64, 0x22, 0x25, 0x0a, 0x0d, 0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x52, 0x65, 0x73,
+ 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x01,
+ 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x32, 0x68, 0x0a, 0x0b, 0x41,
+ 0x75, 0x74, 0x68, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x59, 0x0a, 0x05, 0x4c, 0x6f,
+ 0x67, 0x69, 0x6e, 0x12, 0x19, 0x2e, 0x62, 0x79, 0x74, 0x65, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x76,
+ 0x31, 0x2e, 0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1a,
+ 0x2e, 0x62, 0x79, 0x74, 0x65, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x4c, 0x6f, 0x67,
+ 0x69, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x19, 0x82, 0xd3, 0xe4, 0x93,
+ 0x02, 0x13, 0x3a, 0x01, 0x2a, 0x22, 0x0e, 0x2f, 0x76, 0x32, 0x2f, 0x61, 0x75, 0x74, 0x68, 0x2f,
+ 0x6c, 0x6f, 0x67, 0x69, 0x6e, 0x42, 0x11, 0x5a, 0x0f, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74,
+ 0x65, 0x64, 0x2d, 0x67, 0x6f, 0x2f, 0x76, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
+}
+
+var (
+ file_v1_auth_service_proto_rawDescOnce sync.Once
+ file_v1_auth_service_proto_rawDescData = file_v1_auth_service_proto_rawDesc
+)
+
+func file_v1_auth_service_proto_rawDescGZIP() []byte {
+ file_v1_auth_service_proto_rawDescOnce.Do(func() {
+ file_v1_auth_service_proto_rawDescData = protoimpl.X.CompressGZIP(file_v1_auth_service_proto_rawDescData)
+ })
+ return file_v1_auth_service_proto_rawDescData
+}
+
+var file_v1_auth_service_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
+var file_v1_auth_service_proto_goTypes = []interface{}{
+ (*LoginRequest)(nil), // 0: bytebase.v1.LoginRequest
+ (*LoginResponse)(nil), // 1: bytebase.v1.LoginResponse
+}
+var file_v1_auth_service_proto_depIdxs = []int32{
+ 0, // 0: bytebase.v1.AuthService.Login:input_type -> bytebase.v1.LoginRequest
+ 1, // 1: bytebase.v1.AuthService.Login:output_type -> bytebase.v1.LoginResponse
+ 1, // [1:2] is the sub-list for method output_type
+ 0, // [0:1] is the sub-list for method input_type
+ 0, // [0:0] is the sub-list for extension type_name
+ 0, // [0:0] is the sub-list for extension extendee
+ 0, // [0:0] is the sub-list for field type_name
+}
+
+func init() { file_v1_auth_service_proto_init() }
+func file_v1_auth_service_proto_init() {
+ if File_v1_auth_service_proto != nil {
+ return
+ }
+ if !protoimpl.UnsafeEnabled {
+ file_v1_auth_service_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*LoginRequest); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ file_v1_auth_service_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*LoginResponse); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ }
+ type x struct{}
+ out := protoimpl.TypeBuilder{
+ File: protoimpl.DescBuilder{
+ GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
+ RawDescriptor: file_v1_auth_service_proto_rawDesc,
+ NumEnums: 0,
+ NumMessages: 2,
+ NumExtensions: 0,
+ NumServices: 1,
+ },
+ GoTypes: file_v1_auth_service_proto_goTypes,
+ DependencyIndexes: file_v1_auth_service_proto_depIdxs,
+ MessageInfos: file_v1_auth_service_proto_msgTypes,
+ }.Build()
+ File_v1_auth_service_proto = out.File
+ file_v1_auth_service_proto_rawDesc = nil
+ file_v1_auth_service_proto_goTypes = nil
+ file_v1_auth_service_proto_depIdxs = nil
+}
diff --git a/proto/generated-go/v1/auth_service.pb.gw.go b/proto/generated-go/v1/auth_service.pb.gw.go
new file mode 100644
index 0000000000..131a53ba53
--- /dev/null
+++ b/proto/generated-go/v1/auth_service.pb.gw.go
@@ -0,0 +1,171 @@
+// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
+// source: v1/auth_service.proto
+
+/*
+Package v1 is a reverse proxy.
+
+It translates gRPC into RESTful JSON APIs.
+*/
+package v1
+
+import (
+ "context"
+ "io"
+ "net/http"
+
+ "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
+ "github.com/grpc-ecosystem/grpc-gateway/v2/utilities"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/grpclog"
+ "google.golang.org/grpc/metadata"
+ "google.golang.org/grpc/status"
+ "google.golang.org/protobuf/proto"
+)
+
+// Suppress "imported and not used" errors
+var _ codes.Code
+var _ io.Reader
+var _ status.Status
+var _ = runtime.String
+var _ = utilities.NewDoubleArray
+var _ = metadata.Join
+
+func request_AuthService_Login_0(ctx context.Context, marshaler runtime.Marshaler, client AuthServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var protoReq LoginRequest
+ var metadata runtime.ServerMetadata
+
+ newReader, berr := utilities.IOReaderFactory(req.Body)
+ if berr != nil {
+ return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
+ }
+ if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
+ return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
+ }
+
+ msg, err := client.Login(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
+ return msg, metadata, err
+
+}
+
+func local_request_AuthService_Login_0(ctx context.Context, marshaler runtime.Marshaler, server AuthServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var protoReq LoginRequest
+ var metadata runtime.ServerMetadata
+
+ newReader, berr := utilities.IOReaderFactory(req.Body)
+ if berr != nil {
+ return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
+ }
+ if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
+ return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
+ }
+
+ msg, err := server.Login(ctx, &protoReq)
+ return msg, metadata, err
+
+}
+
+// RegisterAuthServiceHandlerServer registers the http handlers for service AuthService to "mux".
+// UnaryRPC :call AuthServiceServer directly.
+// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906.
+// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterAuthServiceHandlerFromEndpoint instead.
+func RegisterAuthServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server AuthServiceServer) error {
+
+ mux.Handle("POST", pattern_AuthService_Login_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
+ ctx, cancel := context.WithCancel(req.Context())
+ defer cancel()
+ var stream runtime.ServerTransportStream
+ ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
+ inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
+ var err error
+ var annotatedContext context.Context
+ annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/bytebase.v1.AuthService/Login", runtime.WithHTTPPathPattern("/v2/auth/login"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := local_request_AuthService_Login_0(annotatedContext, inboundMarshaler, server, req, pathParams)
+ md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
+ if err != nil {
+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
+ return
+ }
+
+ forward_AuthService_Login_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+
+ })
+
+ return nil
+}
+
+// RegisterAuthServiceHandlerFromEndpoint is same as RegisterAuthServiceHandler but
+// automatically dials to "endpoint" and closes the connection when "ctx" gets done.
+func RegisterAuthServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) {
+ conn, err := grpc.Dial(endpoint, opts...)
+ if err != nil {
+ return err
+ }
+ defer func() {
+ if err != nil {
+ if cerr := conn.Close(); cerr != nil {
+ grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr)
+ }
+ return
+ }
+ go func() {
+ <-ctx.Done()
+ if cerr := conn.Close(); cerr != nil {
+ grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr)
+ }
+ }()
+ }()
+
+ return RegisterAuthServiceHandler(ctx, mux, conn)
+}
+
+// RegisterAuthServiceHandler registers the http handlers for service AuthService to "mux".
+// The handlers forward requests to the grpc endpoint over "conn".
+func RegisterAuthServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
+ return RegisterAuthServiceHandlerClient(ctx, mux, NewAuthServiceClient(conn))
+}
+
+// RegisterAuthServiceHandlerClient registers the http handlers for service AuthService
+// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "AuthServiceClient".
+// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "AuthServiceClient"
+// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in
+// "AuthServiceClient" to call the correct interceptors.
+func RegisterAuthServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client AuthServiceClient) error {
+
+ mux.Handle("POST", pattern_AuthService_Login_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
+ ctx, cancel := context.WithCancel(req.Context())
+ defer cancel()
+ inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
+ var err error
+ var annotatedContext context.Context
+ annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/bytebase.v1.AuthService/Login", runtime.WithHTTPPathPattern("/v2/auth/login"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := request_AuthService_Login_0(annotatedContext, inboundMarshaler, client, req, pathParams)
+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
+ if err != nil {
+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
+ return
+ }
+
+ forward_AuthService_Login_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+
+ })
+
+ return nil
+}
+
+var (
+ pattern_AuthService_Login_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "auth", "login"}, ""))
+)
+
+var (
+ forward_AuthService_Login_0 = runtime.ForwardResponseMessage
+)
diff --git a/proto/generated-go/v1/auth_service_grpc.pb.go b/proto/generated-go/v1/auth_service_grpc.pb.go
new file mode 100644
index 0000000000..8c3d8c68ea
--- /dev/null
+++ b/proto/generated-go/v1/auth_service_grpc.pb.go
@@ -0,0 +1,105 @@
+// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
+// versions:
+// - protoc-gen-go-grpc v1.2.0
+// - protoc (unknown)
+// source: v1/auth_service.proto
+
+package v1
+
+import (
+ context "context"
+ grpc "google.golang.org/grpc"
+ codes "google.golang.org/grpc/codes"
+ status "google.golang.org/grpc/status"
+)
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the grpc package it is being compiled against.
+// Requires gRPC-Go v1.32.0 or later.
+const _ = grpc.SupportPackageIsVersion7
+
+// AuthServiceClient is the client API for AuthService service.
+//
+// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
+type AuthServiceClient interface {
+ Login(ctx context.Context, in *LoginRequest, opts ...grpc.CallOption) (*LoginResponse, error)
+}
+
+type authServiceClient struct {
+ cc grpc.ClientConnInterface
+}
+
+func NewAuthServiceClient(cc grpc.ClientConnInterface) AuthServiceClient {
+ return &authServiceClient{cc}
+}
+
+func (c *authServiceClient) Login(ctx context.Context, in *LoginRequest, opts ...grpc.CallOption) (*LoginResponse, error) {
+ out := new(LoginResponse)
+ err := c.cc.Invoke(ctx, "/bytebase.v1.AuthService/Login", in, out, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+// AuthServiceServer is the server API for AuthService service.
+// All implementations must embed UnimplementedAuthServiceServer
+// for forward compatibility
+type AuthServiceServer interface {
+ Login(context.Context, *LoginRequest) (*LoginResponse, error)
+ mustEmbedUnimplementedAuthServiceServer()
+}
+
+// UnimplementedAuthServiceServer must be embedded to have forward compatible implementations.
+type UnimplementedAuthServiceServer struct {
+}
+
+func (UnimplementedAuthServiceServer) Login(context.Context, *LoginRequest) (*LoginResponse, error) {
+ return nil, status.Errorf(codes.Unimplemented, "method Login not implemented")
+}
+func (UnimplementedAuthServiceServer) mustEmbedUnimplementedAuthServiceServer() {}
+
+// UnsafeAuthServiceServer may be embedded to opt out of forward compatibility for this service.
+// Use of this interface is not recommended, as added methods to AuthServiceServer will
+// result in compilation errors.
+type UnsafeAuthServiceServer interface {
+ mustEmbedUnimplementedAuthServiceServer()
+}
+
+func RegisterAuthServiceServer(s grpc.ServiceRegistrar, srv AuthServiceServer) {
+ s.RegisterService(&AuthService_ServiceDesc, srv)
+}
+
+func _AuthService_Login_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(LoginRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(AuthServiceServer).Login(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/bytebase.v1.AuthService/Login",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(AuthServiceServer).Login(ctx, req.(*LoginRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+// AuthService_ServiceDesc is the grpc.ServiceDesc for AuthService service.
+// It's only intended for direct use with grpc.RegisterService,
+// and not to be introspected or modified (even as a copy)
+var AuthService_ServiceDesc = grpc.ServiceDesc{
+ ServiceName: "bytebase.v1.AuthService",
+ HandlerType: (*AuthServiceServer)(nil),
+ Methods: []grpc.MethodDesc{
+ {
+ MethodName: "Login",
+ Handler: _AuthService_Login_Handler,
+ },
+ },
+ Streams: []grpc.StreamDesc{},
+ Metadata: "v1/auth_service.proto",
+}
diff --git a/proto/v1/auth_service.proto b/proto/v1/auth_service.proto
new file mode 100644
index 0000000000..8a1d039829
--- /dev/null
+++ b/proto/v1/auth_service.proto
@@ -0,0 +1,26 @@
+syntax = "proto3";
+
+package bytebase.v1;
+
+import "google/api/annotations.proto";
+
+option go_package = "generated-go/v1";
+
+service AuthService {
+ rpc Login(LoginRequest) returns (LoginResponse) {
+ option (google.api.http) = {
+ post: "/v2/auth/login"
+ body: "*"
+ };
+ }
+}
+
+message LoginRequest {
+ string email = 1;
+
+ string password = 2;
+}
+
+message LoginResponse {
+ string token = 1;
+}
\ No newline at end of file
diff --git a/server/api/auth/auth.go b/server/api/auth/auth.go
index f5602622e0..e09ca013a6 100644
--- a/server/api/auth/auth.go
+++ b/server/api/auth/auth.go
@@ -7,6 +7,7 @@ import (
"fmt"
"strconv"
"strings"
+ "time"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
@@ -15,12 +16,18 @@ import (
"github.com/golang-jwt/jwt/v4"
+ "github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/common"
"github.com/bytebase/bytebase/store"
)
const (
+ issuer = "bytebase"
+ // Signing key section. For now, this is only used for signing, not for verifying since we only
+ // have 1 version. But it will be used to maintain backward compatibility if we change the signing mechanism.
+ keyID = "v1"
accessTokenAudienceFmt = "bb.user.access.%s"
+ apiTokenDuration = 2 * time.Hour
)
// APIAuthInterceptor is the auth interceptor for gRPC server.
@@ -39,9 +46,20 @@ func New(store *store.Store, secret string, mode common.ReleaseMode) *APIAuthInt
}
}
+var authAllowlistMethods = []string{
+ "/bytebase.v1.AuthService/Login",
+}
+
// UnaryInterceptor is the unary interceptor for gRPC API.
-func (in *APIAuthInterceptor) UnaryInterceptor(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
- // TODO(d): skips auth, actuator, GET /subscription request, OpenAPI SQL endpoint.
+func (in *APIAuthInterceptor) UnaryInterceptor(ctx context.Context, req interface{}, serverInfo *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
+ // TODO(d): skips actuator, GET /subscription request, OpenAPI SQL endpoint.
+ // Skip the allowlisted methods for auth interceptor.
+ for _, allow := range authAllowlistMethods {
+ if strings.HasPrefix(serverInfo.FullMethod, allow) {
+ return handler(ctx, req)
+ }
+ }
+
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, status.Error(codes.PermissionDenied, "failed to parse metadata from incoming context")
@@ -115,3 +133,37 @@ type claims struct {
Name string `json:"name"`
jwt.RegisteredClaims
}
+
+// GenerateAPIToken generates an API token.
+func GenerateAPIToken(user *api.Principal, mode common.ReleaseMode, secret string) (string, error) {
+ expirationTime := time.Now().Add(apiTokenDuration)
+ return generateToken(user, fmt.Sprintf(accessTokenAudienceFmt, mode), expirationTime, []byte(secret))
+}
+
+// Pay attention to this function. It holds the main JWT token generation logic.
+func generateToken(user *api.Principal, aud string, expirationTime time.Time, secret []byte) (string, error) {
+ // Create the JWT claims, which includes the username and expiry time.
+ claims := &claims{
+ Name: user.Name,
+ RegisteredClaims: jwt.RegisteredClaims{
+ Audience: jwt.ClaimStrings{aud},
+ // In JWT, the expiry time is expressed as unix milliseconds.
+ ExpiresAt: jwt.NewNumericDate(expirationTime),
+ IssuedAt: jwt.NewNumericDate(time.Now()),
+ Issuer: issuer,
+ Subject: strconv.Itoa(user.ID),
+ },
+ }
+
+ // Declare the token with the HS256 algorithm used for signing, and the claims.
+ token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
+ token.Header["kid"] = keyID
+
+ // Create the JWT string.
+ tokenString, err := token.SignedString(secret)
+ if err != nil {
+ return "", err
+ }
+
+ return tokenString, nil
+}
diff --git a/server/api/v1/auth_service.go b/server/api/v1/auth_service.go
new file mode 100644
index 0000000000..34767b0806
--- /dev/null
+++ b/server/api/v1/auth_service.go
@@ -0,0 +1,69 @@
+package v1
+
+import (
+ "context"
+
+ "golang.org/x/crypto/bcrypt"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+
+ "github.com/bytebase/bytebase/api"
+ v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"
+ "github.com/bytebase/bytebase/server/api/auth"
+ "github.com/bytebase/bytebase/server/component/config"
+ "github.com/bytebase/bytebase/store"
+)
+
+// AuthService implements the auth service.
+type AuthService struct {
+ v1pb.UnimplementedAuthServiceServer
+ store *store.Store
+ secret string
+ profile *config.Profile
+}
+
+// NewAuthService creates a new AuthService.
+func NewAuthService(store *store.Store, secret string, profile *config.Profile) *AuthService {
+ return &AuthService{
+ store: store,
+ secret: secret,
+ profile: profile,
+ }
+}
+
+// Login is the auth login method.
+func (s *AuthService) Login(ctx context.Context, request *v1pb.LoginRequest) (*v1pb.LoginResponse, error) {
+ user, err := s.store.GetPrincipalByEmail(ctx, request.Email)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, "failed to get principal by email %q", request.Email)
+ }
+ if user == nil {
+ return nil, status.Errorf(codes.NotFound, "user %q not found", request.Email)
+ }
+
+ // Compare the stored hashed password, with the hashed version of the password that was received.
+ if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(request.Password)); err != nil {
+ // If the two passwords don't match, return a 401 status.
+ return nil, status.Errorf(codes.InvalidArgument, "incorrect password")
+ }
+
+ // Test the status of this user.
+ member, err := s.store.GetMemberByPrincipalID(ctx, user.ID)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, "failed to find user member")
+ }
+ if member == nil {
+ return nil, status.Errorf(codes.NotFound, "member not found for email %q", request.Email)
+ }
+ if member.RowStatus == api.Archived {
+ return nil, status.Errorf(codes.NotFound, "This user %q has been deactivated by administrators", request.Email)
+ }
+
+ accessToken, err := auth.GenerateAPIToken(user, s.profile.Mode, s.secret)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, "failed to generate API access token")
+ }
+ return &v1pb.LoginResponse{
+ Token: accessToken,
+ }, nil
+}
diff --git a/server/api/v1/docs.go b/server/api/v1/docs.go
new file mode 100644
index 0000000000..a7960ee7a5
--- /dev/null
+++ b/server/api/v1/docs.go
@@ -0,0 +1,2 @@
+// Package v1 is the implementation of v1 API service.
+package v1
diff --git a/server/api/v1/service.go b/server/api/v1/service.go
deleted file mode 100644
index 8b8e82a0e3..0000000000
--- a/server/api/v1/service.go
+++ /dev/null
@@ -1,21 +0,0 @@
-// Package v1 is the v1 API for Bytebase.
-package v1
-
-import (
- "context"
- "fmt"
-
- "google.golang.org/grpc"
- "google.golang.org/grpc/credentials/insecure"
-
- "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
-
- gw "github.com/bytebase/bytebase/proto/generated-go/v1"
-)
-
-// Register registers the v1api on the grpc server and serveMux.
-func Register(ctx context.Context, grpcServer *grpc.Server, mux *runtime.ServeMux, port int) error {
- gw.RegisterGreeterServiceServer(grpcServer, &GreeterServerImpl{})
- opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}
- return gw.RegisterGreeterServiceHandlerFromEndpoint(ctx, mux, fmt.Sprintf(":%d", port), opts)
-}
diff --git a/server/server.go b/server/server.go
index 666fdd1f78..47e69a4fee 100644
--- a/server/server.go
+++ b/server/server.go
@@ -26,6 +26,9 @@ import (
echoSwagger "github.com/swaggo/echo-swagger"
"go.uber.org/zap"
"google.golang.org/grpc"
+ "google.golang.org/grpc/credentials/insecure"
+
+ v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/common"
@@ -41,7 +44,7 @@ import (
"github.com/bytebase/bytebase/resources/mysqlutil"
"github.com/bytebase/bytebase/resources/postgres"
"github.com/bytebase/bytebase/server/api/auth"
- apiv1 "github.com/bytebase/bytebase/server/api/v1"
+ v1 "github.com/bytebase/bytebase/server/api/v1"
"github.com/bytebase/bytebase/server/component/activity"
"github.com/bytebase/bytebase/server/component/config"
"github.com/bytebase/bytebase/server/component/dbfactory"
@@ -298,7 +301,14 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {
authProvider := auth.New(s.store, s.secret, profile.Mode)
s.grpcServer = grpc.NewServer(grpc.UnaryInterceptor(authProvider.UnaryInterceptor))
mux := runtime.NewServeMux()
- if err := apiv1.Register(ctx, s.grpcServer, mux, profile.GrpcPort); err != nil {
+ v1pb.RegisterGreeterServiceServer(s.grpcServer, &v1.GreeterServerImpl{})
+ v1pb.RegisterAuthServiceServer(s.grpcServer, v1.NewAuthService(s.store, s.secret, &profile))
+ opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}
+ grpcEndpoint := fmt.Sprintf(":%d", profile.GrpcPort)
+ if err := v1pb.RegisterAuthServiceHandlerFromEndpoint(ctx, mux, grpcEndpoint, opts); err != nil {
+ return nil, err
+ }
+ if err := v1pb.RegisterGreeterServiceHandlerFromEndpoint(ctx, mux, grpcEndpoint, opts); err != nil {
return nil, err
}
e.Any("/v2/*", echo.WrapHandler(mux))