|
| 1 | +import crypto from 'crypto'; |
| 2 | +import jwt from 'jsonwebtoken'; |
1 | 3 | import { Request, Response } from 'express'; |
2 | 4 | import { User } from '../models/user_model'; |
3 | 5 | import { hashPassword, comparePassword } from '../utils/password_hash'; |
4 | 6 | import { generateToken } from '../utils/jwt_utils'; |
| 7 | +import { getLinkedInAuthUrl, getLinkedInAccessToken, getLinkedInProfile } from '../utils/linkedin_oauth'; |
| 8 | + |
| 9 | +const JWT_SECRET = process.env.JWT_SECRET || ''; |
5 | 10 |
|
6 | 11 | // Email validation regex |
7 | 12 | const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/; |
@@ -140,7 +145,12 @@ export const login = async (req: Request, res: Response) => { |
140 | 145 | }); |
141 | 146 | } |
142 | 147 |
|
143 | | - // 7 - verify password |
| 148 | + // 7 - verify password (OAuth users won't have a passwordHash) |
| 149 | + if (!user.passwordHash) { |
| 150 | + return res.status(401).json({ |
| 151 | + error: 'This account uses LinkedIn login. Please sign in with LinkedIn.', |
| 152 | + }); |
| 153 | + } |
144 | 154 | const isPasswordValid = await comparePassword(password, user.passwordHash); |
145 | 155 |
|
146 | 156 | if (!isPasswordValid) { |
@@ -173,3 +183,117 @@ export const login = async (req: Request, res: Response) => { |
173 | 183 | } |
174 | 184 | }; |
175 | 185 |
|
| 186 | + |
| 187 | +/** |
| 188 | + * GET /api/auth/linkedin |
| 189 | + * Initiates LinkedIn OAuth flow by redirecting to LinkedIn |
| 190 | + */ |
| 191 | +export const linkedinAuth = async (req: Request, res: Response) => { |
| 192 | + try { |
| 193 | + // Generate CSRF protection state token |
| 194 | + const state = crypto.randomBytes(16).toString('hex'); |
| 195 | + |
| 196 | + // Encode state as JWT with 5-minute expiration (stateless validation) |
| 197 | + const stateToken = jwt.sign({ state }, JWT_SECRET, { expiresIn: '5m' }); |
| 198 | + |
| 199 | + // Build LinkedIn authorization URL and redirect |
| 200 | + const authUrl = getLinkedInAuthUrl(stateToken); |
| 201 | + res.redirect(authUrl); |
| 202 | + } catch (error) { |
| 203 | + console.error('LinkedIn auth initiation error:', error); |
| 204 | + res.status(500).json({ error: 'Failed to initiate LinkedIn authentication' }); |
| 205 | + } |
| 206 | +}; |
| 207 | + |
| 208 | + |
| 209 | +/** |
| 210 | + * GET /api/auth/linkedin/callback |
| 211 | + * LinkedIn redirects here after user authorization |
| 212 | + */ |
| 213 | +export const linkedinCallback = async (req: Request, res: Response) => { |
| 214 | + try { |
| 215 | + const { code, state, error: oauthError } = req.query as { |
| 216 | + code?: string; |
| 217 | + state?: string; |
| 218 | + error?: string; |
| 219 | + }; |
| 220 | + |
| 221 | + const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:19006'; |
| 222 | + |
| 223 | + // Handle user denial |
| 224 | + if (oauthError === 'user_cancelled_authorize') { |
| 225 | + return res.redirect(`${frontendUrl}/auth/error?message=Authorization cancelled`); |
| 226 | + } |
| 227 | + |
| 228 | + // Validate required parameters |
| 229 | + if (!code || !state) { |
| 230 | + return res.status(400).json({ error: 'Missing code or state parameter' }); |
| 231 | + } |
| 232 | + |
| 233 | + // Verify state token (CSRF protection) |
| 234 | + try { |
| 235 | + jwt.verify(state, JWT_SECRET); |
| 236 | + } catch { |
| 237 | + return res.status(401).json({ error: 'Invalid state parameter' }); |
| 238 | + } |
| 239 | + |
| 240 | + // Exchange code for access token |
| 241 | + const accessToken = await getLinkedInAccessToken(code); |
| 242 | + |
| 243 | + // Fetch user profile from LinkedIn |
| 244 | + const linkedinProfile = await getLinkedInProfile(accessToken); |
| 245 | + |
| 246 | + // Validate email is provided |
| 247 | + if (!linkedinProfile.email) { |
| 248 | + return res.status(400).json({ |
| 249 | + error: 'Email address required', |
| 250 | + suggestion: 'Please make your email visible to third-party apps in LinkedIn settings', |
| 251 | + }); |
| 252 | + } |
| 253 | + |
| 254 | + // Find existing user by LinkedIn ID |
| 255 | + let user = await User.findOne({ linkedinId: linkedinProfile.sub }); |
| 256 | + |
| 257 | + if (!user) { |
| 258 | + // Check if email already exists with password auth (email conflict) |
| 259 | + const existingEmailUser = await User.findOne({ |
| 260 | + email: linkedinProfile.email.toLowerCase().trim(), |
| 261 | + }); |
| 262 | + |
| 263 | + if (existingEmailUser) { |
| 264 | + return res.redirect( |
| 265 | + `${frontendUrl}/auth/error?message=Email already registered with password&suggestion=Please login with your password` |
| 266 | + ); |
| 267 | + } |
| 268 | + |
| 269 | + // Create new user from LinkedIn data |
| 270 | + user = await User.create({ |
| 271 | + name: linkedinProfile.name, |
| 272 | + email: linkedinProfile.email.toLowerCase().trim(), |
| 273 | + linkedinId: linkedinProfile.sub, |
| 274 | + profilePhoto: linkedinProfile.picture, |
| 275 | + authProvider: 'linkedin', |
| 276 | + lastLogin: new Date(), |
| 277 | + }); |
| 278 | + } else { |
| 279 | + // Update existing user's last login |
| 280 | + user.lastLogin = new Date(); |
| 281 | + await user.save(); |
| 282 | + } |
| 283 | + |
| 284 | + // Generate JWT token and redirect to frontend |
| 285 | + const token = generateToken(user._id.toString()); |
| 286 | + return res.redirect(`${frontendUrl}/auth/callback?token=${token}&userId=${user._id}`); |
| 287 | + |
| 288 | + } catch (error: any) { |
| 289 | + console.error('LinkedIn callback error:', error); |
| 290 | + |
| 291 | + const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:19006'; |
| 292 | + if (error.message?.includes('LinkedIn')) { |
| 293 | + return res.redirect(`${frontendUrl}/auth/error?message=LinkedIn authentication failed`); |
| 294 | + } |
| 295 | + |
| 296 | + res.status(500).json({ error: 'Authentication failed. Please try again.' }); |
| 297 | + } |
| 298 | +}; |
| 299 | + |
0 commit comments