You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
importexpressfrom"express";import{Model,ObjectId}from"mongoose";importpassportfrom"passport";import{StrategyasAnonymousStrategy}from"passport-anonymous";import{StrategyasJwtStrategy}from"passport-jwt";import{StrategyasLocalStrategy}from"passport-local";import{logger}from"./logger";exportinterfaceUser{_id: ObjectId|string;id: string;// Whether the user should be treated as an admin or not. Admins can have extra abilities in permissions// declarationsadmin: boolean;/** We support anonymous users, which do not yet have login information. This can be helpful for pre-signup users. */isAnonymous?: boolean;token?: string;}exportinterfaceUserModelextendsModel<User>{createAnonymousUser?: (id?: string)=>Promise<User>;postCreate?: (body: any)=>Promise<void>;createStrategy(): any;serializeUser(): any;// Allows additional setup during signup. This will be passed the rest of req.body from the signupdeserializeUser(): any;}exportfunctionauthenticateMiddleware(anonymous=false){conststrategies=["jwt"];if(anonymous){strategies.push("anonymous");}returnpassport.authenticate(strategies,{session: false,failureMessage: true});}exportasyncfunctionsignupUser(userModel: UserModel,email: string,password: string,body?: any){try{constuser=await(userModelasany).register({email},password);if(user.postCreate){deletebody.email;deletebody.password;try{awaituser.postCreate(body);}catch(e){logger.error("Error in user.postCreate",e);throwe;}}awaituser.save();if(!user.token){thrownewError("Token not created");}returnuser;}catch(error){throwerror;}}// TODO allow customizationexportfunctionsetupAuth(app: express.Application,userModel: UserModel){passport.use(newAnonymousStrategy());passport.use("signup",newLocalStrategy({usernameField: "email",passwordField: "password",passReqToCallback: true,},async(req,email,password,done)=>{try{done(undefined,awaitsignupUser(userModel,email,password,req.body));}catch(e){returndone(e);}}));passport.use("login",newLocalStrategy({usernameField: "email",passwordField: "password",},async(email,password,done)=>{try{constuser=awaituserModel.findOne({email});if(!user){logger.warn(`Could not find login user for ${email}`);returndone(null,false,{message: "User Not Found"});}constvalidate=await(userasany).authenticate(password);if(validate.error){logger.warn("Invalid password for",email);returndone(null,false,{message: "Incorrect Password"});}returndone(null,user,{message: "Logged in Successfully"});}catch(error){logger.error("Login error",error);returndone(error);}}));if(!userModel.createStrategy){thrownewError("setupAuth userModel must have .createStrategy()");}if(!userModel.serializeUser){thrownewError("setupAuth userModel must have .serializeUser()");}if(!userModel.deserializeUser){thrownewError("setupAuth userModel must have .deserializeUser()");}// use static serialize and deserialize of model for passport session supportpassport.serializeUser(userModel.serializeUser());passport.deserializeUser(userModel.deserializeUser());if(process.env.TOKEN_SECRET){logger.debug("Setting up JWT Authentication");constcustomExtractor=function(req: express.Request){lettoken=null;if(req?.cookies?.jwt){token=req.cookies.jwt;}elseif(req?.headers?.authorization){token=req?.headers?.authorization.split(" ")[1];}returntoken;};constsecretOrKey=process.env.TOKEN_SECRET;if(!secretOrKey){thrownewError(`TOKEN_SECRET must be set in env.`);}constjwtOpts={// jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme("Bearer"),jwtFromRequest: customExtractor,
secretOrKey,issuer: process.env.TOKEN_ISSUER,};passport.use("jwt",newJwtStrategy(jwtOpts,asyncfunction(payload: {id: string;iat: number;exp: number},done: any){letuser;if(!payload){returndone(null,false);}try{user=awaituserModel.findById((payloadasany).id);}catch(e){logger.warn("[jwt] Error finding user from id",e);returndone(e,false);}if(user){returndone(null,user);}else{if(userModel.createAnonymousUser){logger.info("[jwt] Creating anonymous user");user=awaituserModel.createAnonymousUser();returndone(null,user);}else{logger.info("[jwt] No user found from token");returndone(null,false);}}}));}constrouter=express.Router();router.post("/login",function(req,res,next){passport.authenticate("login",{session: true},(err: any,user: any,info: any)=>{if(err){logger.error("Error logging in:",err);returnnext(err);}if(!user){logger.warn("Invalid login:",info);returnres.status(401).json({message: info?.message});}returnres.json({data: {userId: user?._id,token: (userasany)?.token}});})(req,res,next);});router.post("/signup",passport.authenticate("signup",{session: false,failWithError: true}),asyncfunction(req: any,res: any){returnres.json({data: {userId: req.user._id,token: req.user.token}});});router.get("/me",authenticateMiddleware(),async(req,res)=>{if(!req.user?.id){logger.debug("Not user found for /me");returnres.sendStatus(401);}constdata=awaituserModel.findById(req.user.id);if(!data){logger.debug("Not user data found for /me");returnres.sendStatus(404);}constdataObject=data.toObject();(dataObjectasany).id=data._id;returnres.json({data: dataObject});});router.patch("/me",authenticateMiddleware(),async(req,res)=>{if(!req.user?.id){returnres.sendStatus(401);}constdoc=awaituserModel.findById(req.user.id);if(!doc){returnres.sendStatus(404);}// TODO support limited updates for profile.// try {// body = transform(req.body, "update", req.user);// } catch (e) {// return res.status(403).send({message: (e as any).message});// }try{Object.assign(doc,req.body);awaitdoc.save();constdataObject=doc.toObject();(dataObjectasany).id=doc._id;returnres.json({data: dataObject});}catch(e){returnres.status(403).send({message: (easany).message});}});app.use(express.urlencoded({extended: false})asany);app.use(passport.initialize()asany);app.set("etag",false);app.use("/auth",router);}
f84e5a4e54e14f20bb8868fc849c39c991437241
The text was updated successfully, but these errors were encountered:
support limited updates for profile.
try {
body = transform(req.body, "update", req.user);
} catch (e) {
return res.status(403).send({message: (e as any).message});
}
ferns-api/src/auth.ts
Line 235 in ed93382
f84e5a4e54e14f20bb8868fc849c39c991437241
The text was updated successfully, but these errors were encountered: