1
1
import bcrypt from "bcrypt" ;
2
+
3
+ import admin from "firebase-admin" ;
4
+ import { getAuth } from "firebase-admin/auth" ;
5
+ import serviceAccountKey from "../firebase-adminsdk.json" assert { type : "json " } ;
6
+
2
7
import User from "../Models/user.model.js" ;
3
8
import { formatDataToSend , generateUsername , emailRegex , passwordRegex } from "../utils/helpers.js" ;
4
9
@@ -34,6 +39,8 @@ export const login = async (req, res) => {
34
39
const user = await User . findOne ( { "personal_info.email" : email } ) ;
35
40
if ( ! user ) return res . status ( 404 ) . json ( { error : "Email not found" } ) ;
36
41
42
+ if ( user . google_auth ) return res . status ( 403 ) . json ( { "error" : "This email was signed up with google. Please log in with google to access the account." } ) ;
43
+
37
44
const isMatch = await bcrypt . compare ( password , user . personal_info . password ) ;
38
45
if ( ! isMatch ) return res . status ( 401 ) . json ( { error : "Incorrect password" } ) ;
39
46
@@ -42,3 +49,60 @@ export const login = async (req, res) => {
42
49
return res . status ( 500 ) . json ( { error : "Internal Server Error" } ) ;
43
50
}
44
51
} ;
52
+
53
+ // Google Authorization using Firebase
54
+
55
+ admin . initializeApp ( {
56
+ credential : admin . credential . cert ( serviceAccountKey )
57
+ } )
58
+
59
+ export const googleAuth = async ( req , res ) => {
60
+ let { access_token } = req . body ;
61
+
62
+ try {
63
+ getAuth ( )
64
+ . verifyIdToken ( access_token )
65
+ . then ( async ( decodedUser ) => {
66
+
67
+ let { email, name } = decodedUser ;
68
+
69
+ let user = await User . findOne ( { "personal_info.email" : email } ) . select ( "personal_info.fullname personal_info.username personal_info.profile_img google_auth" ) . then ( ( u ) => {
70
+ return u || null ;
71
+ } )
72
+ . catch ( err => {
73
+ return res . status ( 500 ) . json ( { "error" : err . message } ) ;
74
+ } )
75
+
76
+ if ( user ) {
77
+ // login
78
+ if ( ! user . google_auth ) {
79
+ return res . status ( 403 ) . json ( { "error" : "This email was signed up without google. Please log in with password to access the account." } ) ;
80
+ }
81
+ } else {
82
+ //signup
83
+ let username = await generateUsername ( email ) ;
84
+ user = new User ( {
85
+ personal_info : {
86
+ fullname : name ,
87
+ email,
88
+ username
89
+ } ,
90
+ google_auth : true
91
+ } )
92
+ await user . save ( ) . then ( ( u ) => {
93
+ user = u ;
94
+ } )
95
+ . catch ( err => {
96
+ return res . status ( 500 ) . json ( { "error" : err . message } ) ;
97
+ } )
98
+ }
99
+
100
+ return res . status ( 200 ) . json ( formatDataToSend ( user ) ) ;
101
+ } )
102
+ . catch ( err => {
103
+ return res . status ( 500 ) . json ( { "error" : err . message } ) ;
104
+ } )
105
+ } catch ( err ) {
106
+ return res . status ( 500 ) . json ( { "error" : err . message } ) ;
107
+ }
108
+ }
0 commit comments