memos/api/v2/auth_service.go

42 lines
1.3 KiB
Go
Raw Normal View History

2023-11-30 20:58:36 +08:00
package v2
import (
"context"
"fmt"
2023-11-30 20:58:36 +08:00
"github.com/pkg/errors"
"google.golang.org/grpc"
2023-11-30 21:52:02 +08:00
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
2023-11-30 21:52:02 +08:00
"google.golang.org/grpc/status"
"github.com/usememos/memos/api/auth"
2023-11-30 20:58:36 +08:00
apiv2pb "github.com/usememos/memos/proto/gen/api/v2"
)
func (s *APIV2Service) GetAuthStatus(ctx context.Context, _ *apiv2pb.GetAuthStatusRequest) (*apiv2pb.GetAuthStatusResponse, error) {
user, err := getCurrentUser(ctx, s.Store)
2023-11-30 21:52:02 +08:00
if err != nil {
return nil, status.Errorf(codes.Unauthenticated, "failed to get current user: %v", err)
2023-11-30 20:58:36 +08:00
}
2023-12-06 23:03:24 +08:00
if user == nil {
// Set the cookie header to expire access token.
if err := clearAccessTokenCookie(ctx); err != nil {
return nil, status.Errorf(codes.Internal, "failed to set grpc header")
}
2023-12-06 23:03:24 +08:00
return nil, status.Errorf(codes.Unauthenticated, "user not found")
}
2023-11-30 20:58:36 +08:00
return &apiv2pb.GetAuthStatusResponse{
2023-11-30 21:52:02 +08:00
User: convertUserFromStore(user),
2023-11-30 20:58:36 +08:00
}, nil
}
func clearAccessTokenCookie(ctx context.Context) error {
if err := grpc.SetHeader(ctx, metadata.New(map[string]string{
"Set-Cookie": fmt.Sprintf("%s=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly; SameSite=Strict", auth.AccessTokenCookieName),
})); err != nil {
return errors.Wrap(err, "failed to set grpc header")
}
return nil
}