feat: make social login optional

This commit is contained in:
Lin, Hung-Shin committed 2023-10-05 13:32:02 +08:00
1 parent a79b66ed8d
commit 72b2711367
5 files changed
+145 -49

No files matched your search

+8 -1
View File
@@ -1,5 +1,5 @@
<script setup> <script setup>
import { ref } from 'vue' import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
import { login, register } from '../utils/auth' import { login, register } from '../utils/auth'
import api from '../utils/api' import api from '../utils/api'
@@ -13,6 +13,12 @@ const emailInput = ref(null)
const password = ref('') const password = ref('')
const errorMessage = ref('') const errorMessage = ref('')
const availableMethods = ref({})
onMounted(async () => {
const res = await api.get('/auth/available-methods')
availableMethods.value = res.data
})
const success = () => { const success = () => {
router.push({ name: 'game' }) router.push({ name: 'game' })
} }
@@ -172,6 +178,7 @@ const goBack = () => {
Log in with social account Log in with social account
</p> </p>
<a <a
v-if="availableMethods.google"
class="inline-flex justify-center rounded-lg text-sm font-black py-2 mt-3 bg-icon-google text-text w-full" class="inline-flex justify-center rounded-lg text-sm font-black py-2 mt-3 bg-icon-google text-text w-full"
href="/api/v1/auth/google" href="/api/v1/auth/google"
> >
+15 -8
View File
@@ -1,6 +1,8 @@
import { Router } from 'express' import { Router } from 'express'
import passport from 'passport' import passport from 'passport'
import enabledMethods from '../../auth/passport.js'
import { import {
register, register,
checkUsername, checkUsername,
@@ -26,14 +28,19 @@ router.get('/check-username', checkUsername)
router.get('/check-session', checkSession) router.get('/check-session', checkSession)
router.get('/google', passport.authenticate('google')) router.get('/available-methods', (req, res) => {
res.json(enabledMethods)
})
router.get( if (enabledMethods.google) {
'/google/callback', router.get('/google', passport.authenticate('google'))
passport.authenticate('google', { router.get(
successRedirect: '/', '/google/callback',
failureRedirect: '/login', passport.authenticate('google', {
}) successRedirect: '/',
) failureRedirect: '/login',
})
)
}
export default router export default router
+43 -39
View File
@@ -3,48 +3,52 @@ import GoogleStrategy from 'passport-google-oidc'
import config from '../config.js' import config from '../config.js'
import User from '../models/user.js' import User from '../models/user.js'
console.log('Google config:', config.google) function verify(issuer, profile, cb) {
console.log('Get a google login:', profile)
export default new GoogleStrategy( process.nextTick(async () => {
{ const email = profile.emails[0]?.value
clientID: config.google.clientID, if (!email) {
clientSecret: config.google.clientSecret, cb(new Error('No email found'))
callbackURL: '/api/v1/auth/google/callback', return
scope: ['profile', 'email'], }
},
function verify(issuer, profile, cb) {
console.log('Get a google login:', profile)
process.nextTick(async () => { let user = await User.findOne({ 'google.id': profile.id })
const email = profile.emails[0]?.value if (!user) {
if (!email) { user = await User.findOne({ email })
cb(new Error('No email found')) const google = {
return id: profile.id,
displayName: profile.displayName,
} }
console.log('Existing user:', user)
let user = await User.findOne({ 'google.id': profile.id })
if (!user) { if (!user) {
user = await User.findOne({ email }) user = new User({
const google = { email,
id: profile.id, google,
displayName: profile.displayName, })
} } else if (user.google?.id) {
console.log('Existing user:', user) cb(new Error('Email already used and binded to another account'))
if (!user) { return
user = new User({ } else {
email, user.google = google
google,
})
} else if (user.google?.id) {
cb(new Error('Email already used and binded to another account'))
return
} else {
user.google = google
}
await user.save()
} }
await user.save()
}
cb(null, user) cb(null, user)
}) })
} }
)
const enabled = config.google.clientID && config.google.clientSecret
export default enabled
? new GoogleStrategy(
{
clientID: config.google.clientID,
clientSecret: config.google.clientSecret,
callbackURL: '/api/v1/auth/google/callback',
scope: ['profile', 'email'],
},
verify
)
: null
+13 -1
View File
@@ -5,7 +5,17 @@ import googleStrategy from './googleStrategy.js'
passport.use(passwordStrategy) passport.use(passwordStrategy)
passport.use(jwtStrategy) passport.use(jwtStrategy)
passport.use(googleStrategy)
const enabledMethods = {
local: true,
google: googleStrategy !== null,
}
console.log('Enabled login methods', enabledMethods)
if (enabledMethods.google) {
passport.use(googleStrategy)
}
passport.serializeUser((user, done) => { passport.serializeUser((user, done) => {
process.nextTick(() => { process.nextTick(() => {
@@ -22,3 +32,5 @@ passport.deserializeUser((user, done) => {
done(null, user) done(null, user)
}) })
}) })
export default enabledMethods
+66
View File
@@ -319,6 +319,30 @@ paths:
type: string type: string
example: Username is already taken example: Username is already taken
/auth/available-methods:
get:
summary: Get available login methods
responses:
'200':
description: Available login methods
content:
application/json:
schema:
type: object
properties:
local:
type: boolean
example: true
github:
type: boolean
example: true
google:
type: boolean
example: true
facebook:
type: boolean
example: true
/auth/check-session: /auth/check-session:
get: get:
summary: Check if the session is valid summary: Check if the session is valid
@@ -334,6 +358,36 @@ paths:
type: boolean type: boolean
example: true example: true
/auth/google:
get:
summary: Initiate OAuth2 login with Google
operationId: initiateOAuth
security:
- GoogleOAuth: []
responses:
302:
description: Redirect to Google's OAuth 2.0 authorization endpoint
500:
description: Internal Server Error
/auth/google/callback:
get:
summary: OAuth2 callback endpoint
operationId: oauthCallback
parameters:
- name: code
in: query
description: Authorization code from Google
required: true
schema:
type: string
responses:
200:
description: Successful Operation
400:
description: Bad Request
500:
description: Internal Server Error
/quests: /quests:
get: get:
summary: Get quests list summary: Get quests list
@@ -571,3 +625,15 @@ components:
type: apiKey type: apiKey
in: cookie in: cookie
name: connect.sid name: connect.sid
GoogleOAuth:
type: oauth2
flows:
authorizationCode:
authorizationUrl: https://accounts.google.com/o/oauth2/auth
tokenUrl: https://accounts.google.com/o/oauth2/token
scopes:
# Define your scopes here
openid: OpenID
profile: User profile
email: User email