How to use the Unauthorized function from http-errors

Find comprehensive JavaScript http-errors.Unauthorized code examples handpicked from public code repositorys.

19
20
21
22
23
24
25
26
27
28
badRequest: function badRequest (message) {
  return new createError.BadRequest(message)
},

unauthorized: function unauthorized (message) {
  return new createError.Unauthorized(message)
},

paymentRequired: function paymentRequired (message) {
  return new createError.PaymentRequired(message)
fork icon30
star icon340
watch icon17

+ 55 other calls in file

225
226
227
228
229
230
231
232
233
const kind = 'shoots'
try {
  const user = getUserFromSocket(socket)
  const projectList = await projects.list({ user })
  if (!_.find(projectList, ['metadata.namespace', namespace])) {
    throw new Unauthorized(`Not authorized to subscribe for shoots in namepsace ${namespace}`)
  }

  subscribeShoots(socket, { namespace, filter, user })
fork icon87
star icon0
watch icon2

59
60
61
62
63
64
65
66
67
68
  subject: 'emailAddress'
},
(err, data) => {
  if (err) {
    server.log.error(err)
    return reject(new Unauthorized('Bad Token'))
  }

  resolve(data.emailAddress)
}
fork icon21
star icon1
watch icon2

98
99
100
101
102
103
104
105
106
107
});
let err;
if (!locked) {
        debug("unlocked");
} else if (!user.grants) {
        err = new HttpError.Unauthorized("No user grants");
} else {
        err = new HttpError.Forbidden("No allowed user grants");
}
next(err);
fork icon1
star icon15
watch icon1

84
85
86
87
88
89
90
91
92
93

if (cached) {
  return cached
} else if (cached === null) {
  // null is returned when a previous attempt resulted in the key missing in the JWKs - Do not attemp to fetch again
  throw new Unauthorized(errorMessages.missingKey)
}

// Hit the well-known URL in order to get the key
const response = await fetch(`${domain}.well-known/jwks.json`, { timeout: 5000 })
fork icon27
star icon76
watch icon68

+ 63 other calls in file

226
227
228
229
230
231
232
233
234
235
  if (this.ldapServer.displayAttribute !== undefined) {
    credentials.display = auth[this.ldapServer.displayAttribute];
  }
} catch (_e) {
  this.log("debug", "login", "FINISHED");
  throw new HttpErrors.Unauthorized("Invalid username or password");
}

let user = await User.findOne({
  where: {
fork icon1
star icon8
watch icon0

+ 7 other calls in file

78
79
80
81
82
83
84
85
86
87
88
89
    if(value && value !== KEY_TYPES.VALID) return false   // token is revoked


    return decoded
  } catch (err) {
    console.log(' >>> JWT Token isValid error: ', err)
    throw Error.Unauthorized(MESSAGES.UNAUTHORIZED)
  }
}


module.exports = { create, createNonExpire, decode, renew, isValid, block }
fork icon1
star icon3
watch icon0

1
2
3
4
5
6
7
8
9
10

/* Auth related errors */
module.exports.InvalidAuthToken = new HTTPErrors.Unauthorized(
        'This request requires an authenticated user'
)
module.exports.UnauthorizedUserAccess = new HTTPErrors.Unauthorized(
        'The authorized user is not allowed to access this user'
)
module.exports.InvalidCredentials = new HTTPErrors.Unauthorized(
        'Invalid credentials provided: incorrect email or password'
fork icon1
star icon0
watch icon7

+ 167 other calls in file

42
43
44
45
46
47
48
49
50
51
}

const getCurrentUser = async (req, res, next) => {
  try {
    if (!req.headers || !req.headers['authorization']) {
      throw createError.Unauthorized();
    }

    const authHeader = req.headers['authorization'];
    const bearerToken = authHeader.split(' ');
fork icon0
star icon1
watch icon0

+ 2 other calls in file

40
41
42
43
44
45
46
47
48
49
await checkOtpSchema.validateAsync(req.body);
const { phone, code } = req.body;
const user = await userModel.findOne({ phone });
if (!user) throw createErrors.NotFound("user was not found");
if (user.otp.code != code)
  throw createErrors.Unauthorized("The entered code has incorrect");
const now = Date.now();
//changing data type to number with (+)
if (+user.otp.expiresIn < now)
  throw createErrors.Unauthorized("The entered code has expired");
fork icon0
star icon0
watch icon2

+ 14 other calls in file

106
107
108
109
110
111
112
113
114
115
 */
const now = new Date();

/** return error if otp was expired */
if (user.otp.expires < now)
    throw createError.Unauthorized("کد وارد شده فاقد اعتبار می باشد");

/**
 * create user access token
 * @type {*}
fork icon0
star icon0
watch icon1

+ 23 other calls in file

10
11
12
13
14
15
16
17
18
19
await getOtpSchema.validateAsync(req.body);
const { mobile } = req.body;
const code = randomNumberGenerator()
console.log(`The code is ${code}`);
const result = await this.saveUser(mobile, code)
if (!result) throw createError.Unauthorized("Login Failed")
return res.status(200).send({
  data: {
   
      message: "The code sent successfully",
fork icon0
star icon0
watch icon1

+ 14 other calls in file

31
32
33
34
35
36
37
38
39
40
const { mobile, code } = req.body;
const user = await UserModel.findOne({ mobile }, { password: 0, refreshToken: 0, accessToken: 0})
if (!user) throw createErrors.NotFound("کاربر یافت نشد")
if (user.otp.code != code) throw createErrors.Unauthorized("کد ارسال شده صحیح نمیباشد");
const now = (new Date()).getTime();
if (+user.otp.expiresIn < now) throw createErrors.Unauthorized("کد شما منقضی شده است");
const accessToken = await SignAccessToken(user._id)
const refreshToken = await SignRefreshToken(user._id);
return res.json({
  data: {
fork icon0
star icon0
watch icon1

+ 2 other calls in file

17
18
19
20
21
22
23
24
25
26
try {
    await getOtpSchema.validateAsync(req.body);
    const { mobile } = req.body;
    const code = randomNumberGenerator();
    const result = await this.saveUser(mobile, code);
    if (!result) throw createHttpError.Unauthorized("login failed");
    return res.status(httpStatus.OK).send({
        data: {
            statusCode: httpStatus.OK,
            message: "OTP code successfully sent",
fork icon0
star icon0
watch icon1

+ 8 other calls in file

10
11
12
13
14
15
16
17
18
19
router.post('/login', async (req, res, next) => {
    try {
        const userid = req.body.UserId;
        const user = await User.findOne({UserId:userid});
        if(!user) throw createError.NotFound('Not A Registered User')
        if(user.Password !== req.body.Password) throw createError.Unauthorized('Either User Id or Password is Not Valid')
        const token = await signAccessToken(user.UserId);
        res.cookie("ACCESS_TOKEN" , token,{httpOnly:true, maxAge:600000});
        res.status(200).send({message : "Login Sucessfully"});
    } catch (error) {
fork icon0
star icon0
watch icon1

+ 73 other calls in file

99
100
101
102
103
104
105
106
107
108
}

if (!user) throw createError.NotFound(`No account for ${username}`)

if (!passwordMatch)
  throw createError.Unauthorized('Incorrect login credentials')

if (user.disabled) {
  throw createError.Unauthorized('Account disabled, please contact admin')
}
fork icon0
star icon0
watch icon0

+ 7 other calls in file

53
54
55
56
57
58
59
60
61
62
case 400: {
    httpError = createError.BadRequest();
    break;
}
case 401: {
  httpError = createError.Unauthorized();
  break;
}
case 402: {
  httpError = createError.PaymentRequired();
fork icon0
star icon0
watch icon2

+ 41 other calls in file

92
93
94
95
96
97
98
99
100
101
// check kardane vojode karbari ba in moobile
if (!user)
  throw createHttpError.NotFound("کاربری با این شماره موبایل یافت نشد..");
// check kardane code dar otp
if (user.otp.code != code) {
  throw createHttpError.Unauthorized("کد ارسال شده صحیح نمی باشد.");
}
// check kardane expiresIn dar otp
const now = Date.now();
if (user.otp.exports < now)
fork icon0
star icon0
watch icon1

+ 44 other calls in file

41
42
43
44
45
46
47
48
49
50
const user = await User.findOne({ email: email });
if (!user) throw createError.NotFound("No user found");

// compareing the password
const pswrd = await bcrypt.compare(password, user.password);
if (!pswrd) throw createError.Unauthorized("password is incorrect");

// generating acess-token and refresh-token
const accessToken = await genAccessToken(user);
const refreshToken = await genRefreshToken(user);
fork icon0
star icon0
watch icon0

+ 3 other calls in file

2
3
4
5
6
7
8
9
10
11
12
13
const CONFLICT_ERROR = (msg) => {
  return createHttpError.Conflict({ statusCode: 409, error: msg });
};


const UNAUTHORIZED_ERROR = (msg) => {
  return createHttpError.Unauthorized({ statusCode: 401, error: msg });
};


const NOT_FOUND_ERROR = (msg) => {
  return createHttpError.NotFound({ statusCode: 404, error: msg });
fork icon0
star icon0
watch icon0

+ 3 other calls in file