-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathgithub-auth.service.ts
More file actions
81 lines (76 loc) · 2.8 KB
/
github-auth.service.ts
File metadata and controls
81 lines (76 loc) · 2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import {
Injectable,
Inject,
InternalServerErrorException,
} from "@nestjs/common";
import { IAuthProvider } from "../global/interfaces/oauth.interface";
import { PrismaService } from "../prisma/prisma.service";
import { GithubUser } from "../global/types/auth.types";
import { generatePasswordHash } from "../global/auth/utils";
import { OAuthConfig } from "@/config/Oauth/oauthConfig.interface";
@Injectable()
export class GithubAuthService implements IAuthProvider {
constructor(
private prisma: PrismaService,
@Inject("OAuth-Config") private oAuthConfig: OAuthConfig,
) {}
async validateUser(user: GithubUser) {
const userInDb = await this.prisma.findUserByOAuthId(
"github",
user.githubId,
);
if (userInDb)
return {
id: userInDb.userId,
email: user.email,
};
return this.createUser(user);
}
async createUser(user: GithubUser) {
// generate a random password and not tell them so they can't login, but they will be able to reset password,
// and will be able to login with this in future,
// or maybe the app will prompt user the input the password, exact oauth flow is to be determined
// this should not happen when "user:email" is in the scope
if (!user.email)
throw new InternalServerErrorException(
"[github-auth.service]: Cannot get email from github to create a new Chingu account",
);
// check if email is in the database, add oauth profile to existing account, otherwise, create a new user account
return this.prisma.user.upsert({
where: {
email: user.email,
},
update: {
emailVerified: true,
oAuthProfiles: {
create: {
provider: {
connect: {
name: "github",
},
},
providerUserId: user.githubId,
providerUsername: user.username,
},
},
},
create: {
email: user.email,
password: await generatePasswordHash(),
emailVerified: true,
avatar: user.avatar,
oAuthProfiles: {
create: {
provider: {
connect: {
name: "github",
},
},
providerUserId: user.githubId,
providerUsername: user.username,
},
},
},
});
}
}