Skip to content
This repository has been archived by the owner on Aug 26, 2024. It is now read-only.

Commit

Permalink
Merge pull request #3 from CastyLab/develop
Browse files Browse the repository at this point in the history
Adding add connection with auth token in user service
  • Loading branch information
mrjosh committed Aug 26, 2020
2 parents 0f07586 + 56c538c commit 3070c8e
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 69 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module github.com/CastyLab/grpc.server
go 1.14

require (
github.com/CastyLab/grpc.proto v0.0.0-20200826191006-9099557119fd
github.com/CastyLab/grpc.proto v0.0.0-20200826194833-33423f260a3e
github.com/MrJoshLab/go-respond v0.0.0-20191125172458-25d4d18aaa1b
github.com/asticode/go-astisub v0.2.0
github.com/dgrijalva/jwt-go v3.2.0+incompatible
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,8 @@ github.com/CastyLab/grpc.proto v0.0.0-20200826181838-2f9360028306 h1:rxE+/s9/T0F
github.com/CastyLab/grpc.proto v0.0.0-20200826181838-2f9360028306/go.mod h1:5ypgijUv7rWXMsRbUZXEgTucAA+4BpHtXgGIvOyUGRU=
github.com/CastyLab/grpc.proto v0.0.0-20200826191006-9099557119fd h1:FBfJeHIVSQ8mCDTg1WP3FQRjpFpC0d67Zvc1uq+0UxQ=
github.com/CastyLab/grpc.proto v0.0.0-20200826191006-9099557119fd/go.mod h1:5ypgijUv7rWXMsRbUZXEgTucAA+4BpHtXgGIvOyUGRU=
github.com/CastyLab/grpc.proto v0.0.0-20200826194833-33423f260a3e h1:oHGrPtr768HDVO7FYVGCIBwvU5PwFO620IVjwb9lslI=
github.com/CastyLab/grpc.proto v0.0.0-20200826194833-33423f260a3e/go.mod h1:5ypgijUv7rWXMsRbUZXEgTucAA+4BpHtXgGIvOyUGRU=
github.com/CloudyKit/fastprinter v0.0.0-20170127035650-74b38d55f37a/go.mod h1:EFZQ978U7x8IRnstaskI3IysnWY5Ao3QgZUKOXlsAdw=
github.com/CloudyKit/jet v2.1.3-0.20180809161101-62edd43e4f88+incompatible/go.mod h1:HPYO+50pSWkPoj9Q/eq0aRGByCL6ScRlUmiEX5Zgm+w=
github.com/Joker/hpp v1.0.0/go.mod h1:8x5n+M1Hp5hC0g8okX3sR3vFQwynaX/UgSOM9MeBKzY=
Expand Down
119 changes: 51 additions & 68 deletions services/auth/oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,32 +11,35 @@ import (
"github.com/CastyLab/grpc.server/oauth/discord"
"github.com/CastyLab/grpc.server/oauth/google"
"github.com/CastyLab/grpc.server/oauth/spotify"
"github.com/CastyLab/grpc.server/services"
"github.com/getsentry/sentry-go"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"golang.org/x/oauth2"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"log"
"net/http"
"time"
)

func (Service) CallbackOAUTH(ctx context.Context, req *proto.OAUTHRequest) (*proto.AuthResponse, error) {

var (
err error
authenticated bool
token *oauth2.Token
oauthUser oauth.User
user = new(models.User)
collection = db.Connection.Collection("users")
consCollection = db.Connection.Collection("connections")
unauthorized = status.Error(codes.Unauthenticated, "Unauthorized!")
)

var (
token *oauth2.Token
err error
oauthUser oauth.User
)
if req.AuthRequest != nil {
user, err = Authenticate(req.AuthRequest)
if err != nil {
return nil, err
}
authenticated = true
}

switch req.Service {
case proto.Connection_SPOTIFY:
Expand Down Expand Up @@ -67,84 +70,64 @@ func (Service) CallbackOAUTH(ctx context.Context, req *proto.OAUTHRequest) (*pro
return nil, unauthorized
}
default:
return nil, unauthorized
}

filter := bson.M{
"service_user_id": oauthUser.GetUserId(),
"type": req.Service,
"user_id": user.ID,
}

consCount, err := consCollection.CountDocuments(ctx, filter)
if err != nil {
return nil, status.Error(codes.Unavailable, "Could not create connection, Please try again later!")
return nil, status.Error(codes.InvalidArgument, "Invalid oauth service")
}

if consCount == 0 {
connection := bson.M{
if authenticated {
filter := bson.M{
"service_user_id": oauthUser.GetUserId(),
"name": oauthUser.GetFullname(),
"type": req.Service,
"access_token": token.AccessToken,
"refreshed_token": token.RefreshToken,
"show_activity": true,
"user_id": user.ID,
"created_at": time.Now(),
"updated_at": time.Now(),
}
if _, err := consCollection.InsertOne(ctx, connection); err != nil {
sentry.CaptureException(fmt.Errorf("could not create connection :%v", err))
consCount, err := consCollection.CountDocuments(ctx, filter)
if err != nil {
return nil, status.Error(codes.Unavailable, "Could not create connection, Please try again later!")
}
if consCount == 0 {
connection := bson.M{
"service_user_id": oauthUser.GetUserId(),
"name": oauthUser.GetFullname(),
"type": req.Service,
"access_token": token.AccessToken,
"refreshed_token": token.RefreshToken,
"show_activity": true,
"user_id": user.ID,
"created_at": time.Now(),
"updated_at": time.Now(),
}
if _, err := consCollection.InsertOne(ctx, connection); err != nil {
sentry.CaptureException(fmt.Errorf("could not create connection :%v", err))
return nil, status.Error(codes.Unavailable, "Could not create connection, Please try again later!")
}
return &proto.AuthResponse{
Status: "success",
Code: http.StatusOK,
Message: "Connection created successfully!",
}, nil
}
}

var (
userObjectId string
cursor = collection.FindOne(ctx, bson.M{
"email": oauthUser.GetEmailAddress(),
})
)

if err := cursor.Decode(&user); err != nil {

avatarName, err := services.SaveAvatarFromUrl(oauthUser.GetAvatar())
if err != nil {
log.Println(err)
avatarName = "default"
connection = new(models.Connection)
filter = bson.M{
"service_user_id": oauthUser.GetUserId(),
}
)

dbUser := bson.M{
"fullname": oauthUser.GetFullname(),
"hash": services.GenerateHash(),
"username": services.RandomUserName(),
"email": oauthUser.GetEmailAddress(),
"password": models.HashPassword(services.RandomString(20)),
"is_active": true,
"verified": false,
"is_staff": false,
"email_verified": false,
"email_token": services.RandomString(40),
"state": int(proto.PERSONAL_STATE_OFFLINE),
"activity": bson.M{},
"avatar": avatarName,
"last_login": time.Now(),
"joined_at": time.Now(),
"updated_at": time.Now(),
}
if err := consCollection.FindOne(ctx, filter).Decode(connection); err != nil {
return nil, unauthorized
}

result, err := collection.InsertOne(ctx, dbUser)
if err != nil {
return nil, status.Error(codes.Internal, "Could not create the user, Please try again later!")
}
userObjectId = result.InsertedID.(primitive.ObjectID).Hex()
err = collection.FindOne(ctx, bson.M{ "_id": connection.UserId }).Decode(user)
if err != nil {
return nil, unauthorized
}

if user.ID != nil {
userObjectId = user.ID.Hex()
if user.ID != connection.UserId {
return nil, unauthorized
}

authToken, refreshedToken, err := jwt.CreateNewTokens(ctx, userObjectId)
authToken, refreshedToken, err := jwt.CreateNewTokens(ctx, user.ID.Hex())
if err != nil {
return nil, unauthorized
}
Expand Down

0 comments on commit 3070c8e

Please sign in to comment.