File size: 2,207 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// @flow
import Raven from 'shared/raven';
import type { GraphQLContext } from '../../';
import type { EditUserInput } from 'shared/db/queries/user';
import UserError from '../../utils/UserError';
import {
  getUserByUsername,
  editUser,
  getUsersByEmail,
  setUserPendingEmail,
} from 'shared/db/queries/user';
import { isAuthedResolver as requireAuth } from '../../utils/permissions';
import isEmail from 'validator/lib/isEmail';

export default requireAuth(
  async (_: any, args: EditUserInput, ctx: GraphQLContext) => {
    const { user: currentUser, updateCookieUserData } = ctx;
    const { input } = args;

    // If the user is trying to change their username check whether there's a person with that username already
    if (input.username) {
      if (input.username === 'null' || input.username === 'undefined') {
        return new UserError('Nice try! 😉');
      }

      const dbUser = await getUserByUsername(input.username);
      if (dbUser && dbUser.id !== currentUser.id) {
        return new UserError(
          'Looks like that username got swooped! Try another?'
        );
      }
    }

    if (input.email && typeof input.email === 'string') {
      const pendingEmail = input.email;

      // if user is changing their email, make sure it's not taken by someone else
      if (pendingEmail !== currentUser.email || !currentUser.email) {
        if (!isEmail(input.email)) {
          return new UserError('Please enter a valid email address.');
        }

        const dbUsers = await getUsersByEmail(pendingEmail);
        if (dbUsers && dbUsers.length > 0) {
          return new UserError('Please enter a valid email address.');
        }

        // the user will have to confirm their email for it to be saved in
        // order to prevent spoofing your email as someone elses
        await setUserPendingEmail(currentUser.id, pendingEmail);
      }
    }

    const editedUser = await editUser(args, currentUser.id);

    await updateCookieUserData({
      ...editedUser,
    }).catch(err => {
      Raven.captureException(
        new Error(`Error updating cookie user data: ${err.message}`)
      );
      return editedUser;
    });

    return editedUser;
  }
);