Advertisement
Guest User

Untitled

a guest
Jul 4th, 2016
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.50 KB | None | 0 0
  1. package com.userapi.spring.controller;
  2.  
  3. @RestController
  4. @RequestMapping("user")
  5. @Component
  6. public class UserController {
  7. @Autowired
  8. UserCredentialService userCredService; // Just a DAO
  9.  
  10. @Autowired
  11. ConfirmHandler handler;
  12.  
  13. @Autowired
  14. UserService userService; // Just a DAO
  15.  
  16. @Autowired
  17. JwtTokenServiceImpl jwtServ;
  18.  
  19. // Used to grab data from our redis store...
  20. RedisClient redisClient = new RedisClient();
  21.  
  22. // #TODO should these be up here or should I create a new UserCredential in each of the endpoints
  23. UserCredential userCredential = null;
  24.  
  25. @CrossOrigin
  26. @RequestMapping(value="login/facebook", method=RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE })
  27. ResponseEntity<?> login(@RequestBody UserFacebookLoginContext body) throws IOException, InvalidKeySpecException,
  28. NoSuchAlgorithmException, ConfirmLogin, ClassNotFoundException, ConfirmResponse, InvalidRequestException, ConfirmLoginEmail {
  29.  
  30. long fbId;
  31. String fbToken = body.getFacebookToken();
  32. String email = null;
  33. if (fbToken.equals("") || fbToken.length() < 10) throw new Error("Invalid facebook token"); // Quick check on fb token
  34. // Create new user entity (auth_user)
  35. String hashPassword = userService.hashPassword("hashxx--29");
  36.  
  37. // Make call to graph and check if data is returned
  38. FacebookClient facebookClient = new DefaultFacebookClient(fbToken, Version.LATEST);
  39. com.restfb.types.User userData = facebookClient.fetchObject("me",
  40. com.restfb.types.User.class, Parameter.with("fields", "id,email,hometown,cover,name,picture"));
  41.  
  42. // Check if token was valid, grab email + id
  43. if (userData.getEmail() != null
  44. && userData.getHometown() != null && userData.getId() != null) {
  45. fbId = Long.parseLong(userData.getId());
  46. email = userData.getEmail();
  47. } else {
  48.  
  49. throw new InvalidRequestException("Invalid facebook login");
  50. // throw new Error("Invalid facebook login"); // TODO add generic error class which spits back approriate msgs
  51. }
  52.  
  53. // Simply serializes the returned facebook graph data into a Java obj
  54. FacebookDataSerializer fbUser = new FacebookDataSerializer(userData);
  55.  
  56. // Create JSON string from fbdata
  57. ObjectMapper mapper = new ObjectMapper();
  58. String fbJson = mapper.writeValueAsString(fbUser); // We save this in a DB field (just dumping it for now)
  59.  
  60. // Find existing user credentials for this email #TODO change findBYExternalId so it returns a user credential not list
  61. List<UserCredential> foundUserEmail = userCredService.findByEmail(userData.getEmail());
  62. // Filter out found users by externalId
  63. List<UserCredential> foundUsers = foundUserEmail.stream().filter(u -> u.getExternalId() == fbId)
  64. .collect(Collectors.toList());
  65.  
  66.  
  67. // If a credential exists, check if it matches the parsed email + passsowrd + account type -
  68. if (foundUserEmail.size() > 0 && foundUsers.size() == 0) {
  69.  
  70. // Create new user credential #TODO make re-usable with the below user credential....
  71. userCredential = new UserCredential(
  72. fbId,
  73. foundUserEmail.get(0).getUserId(),
  74. new Date(),
  75. email,
  76. "facebook",
  77. hashPassword,
  78. fbJson
  79. );
  80.  
  81. // This sends an email to the user with a link that they must click to merge the two accounts
  82. ConfirmHandler handler = new ConfirmHandler(userCredential);
  83. handler.storeConfirmationObject(); // Store in redis...
  84.  
  85. // Return a custom message object in respinse entiy
  86. ConfirmResponse r = new ConfirmResponse("Error", 111, "An account already exists under this email",
  87. "Please goto your email (" + userCredential.getEmail() + ") and confirm to login!",
  88. "You must goto your email, click the 'create account' button, and then you'll be redirected to our site!");
  89.  
  90.  
  91. } else if (foundUsers.size() > 0) {
  92. System.out.println("nFb user is valid...return foundUsers.credential" + email);
  93. userCredential = foundUsers.get(0);
  94. if (!userCredential.getEmail().equals(email)) throw new Error("Something strange going on"); // Just incase something weird is going on...
  95. userCredential.setUserdataJson(fbJson);
  96. } else {
  97. // Replaces setters with constructor (#TODO should I use setters instead)??
  98. User user = new User(
  99. fbUser.getFirstname(),
  100. fbUser.getLastname(),
  101. 0, // is admin user
  102. hashPassword,
  103. email,
  104. email, // Username (storing email for now)
  105. 1, // is normal user
  106. 0, // is staff user
  107. new Date(),
  108. new Date()
  109. );
  110.  
  111. // Create new user credential (should I use getters or constructor)
  112. userCredential = new UserCredential(
  113. fbId,
  114. user.getUserId(), // Grab the userId from the found or created user entity
  115. new Date(),
  116. email,
  117. "facebook",
  118. hashPassword,
  119. fbJson
  120. );
  121. // Save user credential to database
  122. userCredService.saveUserCredential(userCredential);
  123. }
  124.  
  125. // Create new JWT
  126. JwtToken jwt = new JwtToken();
  127.  
  128. // Create JWT for usercredential (userId) and simply return
  129. return new ResponseEntity<>(new FbLoginResponse(jwt.getToken(), fbUser), HttpStatus.OK); // Returns fb graph data + JWT
  130.  
  131. }
  132.  
  133. @CrossOrigin
  134. @RequestMapping(value="/api/v1/logout/", method=RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE })
  135. LogoutResponse deleteToken(final HttpServletRequest request) throws ServletException {
  136. final Claims claims = (Claims) request.getAttribute("claims");
  137. System.out.println(request.getAttribute("token")+ " <~~~ About to logout user");
  138.  
  139. boolean didLogout = redisClient.delete(request.getAttribute("token").toString());
  140. return new LogoutResponse("Logged out", !didLogout);
  141. }
  142.  
  143.  
  144. @RequestMapping(value="login/email", method=RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE })
  145. LoginResponse login(@RequestBody UserEmailLoginContext body) throws InvalidKeySpecException, NoSuchAlgorithmException, ConfirmLogin, IOException, ClassNotFoundException {
  146. String email = body.getEmail();
  147. String password = body.getPassword();
  148.  
  149. if (email.equals("")) throw new Error("No email provided");
  150. else if (password.equals(""))throw new Error("No password provided");
  151. String hashPassword = userService.hashPassword(password);
  152. List<UserCredential> foundUsers = userCredService.findByEmail(email); // #TODO move to just single usercredential
  153.  
  154. // If a credential exists, check if it matches the passed email + password + account type
  155. if (foundUsers.size() > 0) {
  156. userCredential = userCredService.isValidUserLogin(foundUsers, email, password);
  157. if (userCredential == null) {
  158. // Determine whether there are other credential types in the isValidUserLogin method
  159. // instead of throwing an error to end the program
  160. throw new Error("Invalid user");
  161. }
  162. } else {
  163. // Create new user entity (auth_user)
  164. User user = new User();
  165. user.setEmail(email);
  166. user.setPassword(hashPassword);
  167. user.setFirstName(email);
  168. user.setLastName(email);
  169. user.setUsername(email);
  170. user.setDateJoined(new Date());
  171. user.setIsStaff(0);
  172. userService.saveUser(user);
  173.  
  174. // Create new user credential with the passed email + password
  175. userCredential = new UserCredential();
  176. userCredential.setUserId(user.getUserId());
  177. userCredential.setEmail(email);
  178. userCredential.setPassword(user.getPassword());
  179. userCredential.setAccountType("email");
  180. userCredential.setCreated(new Date());
  181. userCredential.setUserdataJson("");
  182. userCredService.saveUserCredential(userCredential);
  183. }
  184.  
  185.  
  186. JwtToken jwt = new JwtToken();
  187.  
  188.  
  189. return new LoginResponse(jwt.getToken());
  190. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement