diff --git a/src/main/java/com/planets/app/config/WebAppConfig.java b/src/main/java/com/planets/app/config/WebAppConfig.java index 23a3005..7cc8201 100644 --- a/src/main/java/com/planets/app/config/WebAppConfig.java +++ b/src/main/java/com/planets/app/config/WebAppConfig.java @@ -9,6 +9,8 @@ */ package com.planets.app.config; +import org.h2.server.web.WebServlet; +import org.springframework.boot.context.embedded.ServletRegistrationBean; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.orm.jpa.EntityScan; import org.springframework.context.annotation.Bean; @@ -50,5 +52,13 @@ public AppRestInterceptor restInterceptor() { public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(restInterceptor()).addPathPatterns("/**"); } + + @Bean + public ServletRegistrationBean h2servletRegistration() { + ServletRegistrationBean registrationBean = new ServletRegistrationBean(new WebServlet()); + registrationBean.addUrlMappings("/admin/h2console/*"); + registrationBean.addInitParameter("-webAllowOthers", "true"); + return registrationBean; + } } diff --git a/src/main/java/com/planets/app/controller/AdminController.java b/src/main/java/com/planets/app/controller/AdminController.java deleted file mode 100644 index 2cc0bf8..0000000 --- a/src/main/java/com/planets/app/controller/AdminController.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * AdminController.java - * - * Version: - * $Id$ - * - * Revisions: - * $Log$ - */ -package com.planets.app.controller; - -import static edu.tamu.framework.enums.ApiResponseType.SUCCESS; - -import java.util.HashMap; -import java.util.Map; - -import org.springframework.messaging.handler.annotation.MessageMapping; -import org.springframework.messaging.handler.annotation.SendTo; -import org.springframework.web.bind.annotation.RestController; - -import edu.tamu.framework.aspect.annotation.Auth; -import edu.tamu.framework.aspect.annotation.Data; -import edu.tamu.framework.model.ApiResponse; - -/** - * Admin Controller. - * - */ -@RestController -@MessageMapping("/admin") -public class AdminController { - - /** - * Websocket endpoint to request to broadcast message. - * - * @param data - * String - * @return ApiResponse - * - * @throws Exception - * - */ - @MessageMapping("/broadcast") - @SendTo("/channel/admin/broadcast") - @Auth(role = "ROLE_ADMIN") - public ApiResponse broadcast(@Data String data) throws Exception { - Map messageMap = new HashMap(); - messageMap.put("message", data); - return new ApiResponse(SUCCESS, messageMap); - } - -} \ No newline at end of file diff --git a/src/main/java/com/planets/app/controller/AppAuthController.java b/src/main/java/com/planets/app/controller/AppAuthController.java deleted file mode 100644 index 6657446..0000000 --- a/src/main/java/com/planets/app/controller/AppAuthController.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * AppAuthController.java - * - * Version: - * $Id$ - * - * Revisions: - * $Log$ - */ -package com.planets.app.controller; - -import static edu.tamu.framework.enums.ApiResponseType.ERROR; -import static edu.tamu.framework.enums.ApiResponseType.SUCCESS; -import static org.springframework.web.bind.annotation.RequestMethod.POST; - -import java.io.UnsupportedEncodingException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import javax.crypto.BadPaddingException; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.web.bind.annotation.RestController; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.planets.app.model.AppUser; -import com.planets.app.model.repo.AppUserRepo; - -import edu.tamu.framework.aspect.annotation.ApiMapping; -import edu.tamu.framework.aspect.annotation.Data; -import edu.tamu.framework.aspect.annotation.Parameters; -import edu.tamu.framework.controller.CoreAuthController; -import edu.tamu.framework.model.ApiResponse; - -/** - * - * - */ -@RestController -@ApiMapping("/auth") -public class AppAuthController extends CoreAuthController { - - @Autowired - private AppUserRepo userRepo; - - @Value("${app.authority.admins}") - private String[] admins; - - @Value("${app.ui.host}") - private String uiHost; - - /** - * - */ - @Override - @ApiMapping(value = "/register", method = POST) - public ApiResponse registration(@Data String data, @Parameters Map parameters) { - - if (parameters.get("email") != null) { - - String email = parameters.get("email")[0]; - - if (userRepo.findByEmail(email) != null) { - logger.debug("Account with email " + email + " already exists!"); - return new ApiResponse(ERROR, "Account with email " + email + " already exists!"); - } - - String subject = "Registration"; - String content = "Email Verifiaction. Follow link to continue registration.\n\n"; - - try { - content += uiHost + "/register?token=" + authUtility.generateToken(email, EMAIL_VERIFICATION_TYPE); - } catch (InvalidKeyException | NoSuchPaddingException | NoSuchAlgorithmException | IllegalBlockSizeException | BadPaddingException e1) { - logger.debug("Unable to generate token! " + email); - return new ApiResponse(ERROR, "Unable to generate token! " + email); - } - - try { - emailSender.sendEmail(email, subject, content); - } catch (Exception e) { - logger.debug("Unable to send email! " + email); - return new ApiResponse(ERROR, "Unable to send email! " + email); - } - - return new ApiResponse(SUCCESS, "An email has been sent to " + email + ". Please verify email to continue registration.", parameters); - } - - Map dataMap = new HashMap(); - try { - dataMap = objectMapper.readValue(data, new TypeReference>() { - }); - } catch (Exception e) { - e.printStackTrace(); - } - - String token = dataMap.get("token"); - String firstName = dataMap.get("firstName"); - String lastName = dataMap.get("lastName"); - String password = dataMap.get("password"); - String confirm = dataMap.get("confirm"); - - if ((firstName == null || firstName.trim().length() == 0) && (lastName == null || lastName.trim().length() == 0)) { - logger.debug("Either a first or last name is required!"); - return new ApiResponse(ERROR, "Either a first or last name is required!"); - } - - if (password == null || password.trim().length() == 0) { - logger.debug("Registration requires a password!"); - return new ApiResponse(ERROR, "Registration requires a password!"); - } - - if (password != null && !password.equals(confirm)) { - logger.debug("The passwords do not match!"); - return new ApiResponse(ERROR, "The passwords do not match!"); - } - - if (password != null && password.trim().length() < 6) { - logger.debug("Password must be greater than 6 characters!"); - return new ApiResponse(ERROR, "Password must be greater than 6 characters!"); - } - - String[] content = null; - try { - content = authUtility.validateToken(token, EMAIL_VERIFICATION_TYPE); - } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) { - logger.debug("Unable to validate token!"); - return new ApiResponse(ERROR, "Unable to generate token!"); - } - - String tokenCreateTime = content[0]; - String email = content[1]; - - Long tokenDaysOld = TimeUnit.MILLISECONDS.toDays(Long.valueOf(tokenCreateTime) - new Date().getTime()); - - if (tokenDaysOld >= 2) { - logger.debug("Token has expired!"); - return new ApiResponse(ERROR, "Token has expired! Please begin registration again."); - } - - AppUser user = userRepo.create(email, firstName, lastName); - user.setPassword(authUtility.encodePassword(password)); - - user.setRole("ROLE_USER"); - - for (String admin : admins) { - if (admin.equals(user.getEmail())) { - user.setRole("ROLE_ADMIN"); - } - } - - user = userRepo.save(user); - - return new ApiResponse(SUCCESS, "Registration successful. Please login.", user); - } - - /** - * - */ - @Override - @ApiMapping("/login") - public ApiResponse login(@Data String data) { - - Map dataMap = new HashMap(); - try { - dataMap = objectMapper.readValue(data, new TypeReference>() { - }); - } catch (Exception e) { - return new ApiResponse(ERROR, "Could not map input data!"); - } - - String email = dataMap.get("email"); - String password = dataMap.get("password"); - - AppUser user = userRepo.findByEmail(email); - - if (user == null) { - logger.debug("No user found with email " + email + "!"); - return new ApiResponse(ERROR, "No user found with email " + email + "!"); - } - - if (!authUtility.validatePassword(password, user.getPassword())) { - logger.debug("Authentication failed!"); - return new ApiResponse(ERROR, "Authentication failed!"); - } - - Map payload = new HashMap(); - - payload.put("lastName", user.getLastName()); - payload.put("firstName", user.getFirstName()); - payload.put("uin", String.valueOf(user.getUin())); - payload.put("email", user.getEmail()); - - try { - return new ApiResponse(SUCCESS, jwtUtility.makeToken(payload)); - } catch (InvalidKeyException | JsonProcessingException | NoSuchAlgorithmException | IllegalStateException | UnsupportedEncodingException e) { - logger.debug("Unable to generate token!"); - return new ApiResponse(ERROR, "Unable to generate token!"); - } - } - -} diff --git a/src/main/java/com/planets/app/controller/AuthController.java b/src/main/java/com/planets/app/controller/AuthController.java new file mode 100644 index 0000000..9830f00 --- /dev/null +++ b/src/main/java/com/planets/app/controller/AuthController.java @@ -0,0 +1,96 @@ +package com.planets.app.controller; + +import java.io.UnsupportedEncodingException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.util.HashMap; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.RequestMethod; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.planets.app.model.AppUser; +import com.planets.app.model.repo.AppUserRepo; + +import static edu.tamu.framework.enums.ApiResponseType.SUCCESS; +import static edu.tamu.framework.enums.ApiResponseType.ERROR; +import edu.tamu.framework.aspect.annotation.ApiMapping; +import edu.tamu.framework.aspect.annotation.Data; +import edu.tamu.framework.aspect.annotation.Parameters; +import edu.tamu.framework.controller.CoreAuthController; +import edu.tamu.framework.model.ApiResponse; + +@Controller +@ApiMapping("/auth") +public class AuthController extends CoreAuthController { + + @Autowired + AppUserRepo appUserRepo; + + @ApiMapping(value="/login", method=RequestMethod.POST) + public ApiResponse login(@Parameters Map parameters) { + + String email = parameters.get("email")[0]; + String password = parameters.get("password")[0]; + + AppUser user = appUserRepo.findByEmail(email); + + if(user == null) { + String errorMessage = "No user found with email " + email + "!"; + logger.debug(errorMessage); + return new ApiResponse(ERROR, errorMessage); + } + + if(!authUtility.validatePassword(password, user.getPassword())) { + String errorMessage = "Authentication failed!"; + logger.debug(errorMessage); + return new ApiResponse(ERROR, errorMessage); + } + + try { + Map userMap = new HashMap(); + userMap.put("lastName", user.getLastName()); + userMap.put("firstName", user.getFirstName()); + userMap.put("uin", String.valueOf(user.getUin())); + userMap.put("email", user.getEmail()); + return new ApiResponse(SUCCESS, jwtUtility.makeToken(userMap)); + } catch (InvalidKeyException | JsonProcessingException | NoSuchAlgorithmException | IllegalStateException | UnsupportedEncodingException e) { + logger.debug("Unable to generate token!"); + return new ApiResponse(ERROR, "Unable to generate token!"); + } + } + + @ApiMapping(value="/register", method=RequestMethod.POST) + @Transactional + public ApiResponse registration(@Parameters Map parameters) { + ApiResponse apiResponse = null; + + if( parameters.get("email") == null + || parameters.get("password") == null + ) { + + String error = "Missing neccessary information:"; + + error = parameters.get("email") == null ? (error + " email") : error; + error = parameters.get("password") == null ? (error + " pssword") : error; + + apiResponse = new ApiResponse(ERROR, error); + } else { + + System.out.println(authUtility); + AppUser user = appUserRepo.create(parameters.get("email")[0], "", "", authUtility.encodePassword(parameters.get("password")[0])); + user.setRole("ROLE_USER"); + appUserRepo.save(user); + apiResponse = new ApiResponse(SUCCESS, "The email " +parameters.get("email")[0]+" was registered.", user); + } + + return apiResponse; + } + + public ApiResponse login(@Data String data) {return null;} + public ApiResponse registration(String data, @Parameters Map parameters) {return null;} + +} diff --git a/src/main/java/com/planets/app/controller/ThemeController.java b/src/main/java/com/planets/app/controller/ThemeController.java deleted file mode 100644 index 28a5c4f..0000000 --- a/src/main/java/com/planets/app/controller/ThemeController.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * ThemeController.java - * - * Version: - * $Id$ - * - * Revisions: - * $Log$ - */ -package com.planets.app.controller; - -import static edu.tamu.framework.enums.ApiResponseType.SUCCESS; - -import java.io.IOException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.messaging.simp.SimpMessagingTemplate; -import org.springframework.stereotype.Controller; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import edu.tamu.framework.aspect.annotation.ApiMapping; -import edu.tamu.framework.aspect.annotation.Auth; -import edu.tamu.framework.aspect.annotation.Data; -import edu.tamu.framework.model.ApiResponse; -import edu.tamu.framework.model.CoreTheme; -import edu.tamu.framework.model.repo.CoreThemeRepo; -import edu.tamu.framework.service.ThemeManagerService; - -/** - * - */ -@Controller -@ApiMapping("/theme") -public class ThemeController { - - @Autowired - private ObjectMapper objectMapper; - - @Autowired - private SimpMessagingTemplate simpMessagingTemplate; - - @Autowired - private CoreThemeRepo coreThemeRepo; - - @Autowired - private ThemeManagerService themeManagerService; - - /** - * - * @return - */ - @ApiMapping("/all") - @Auth(role = "ROLE_ADMIN") - public ApiResponse getAll() { - Map> coreThemes = new HashMap>(); - coreThemes.put("list", coreThemeRepo.findAll()); - return new ApiResponse(SUCCESS, coreThemes); - } - - /** - * - * @param data - * @return - * @throws IOException - */ - @ApiMapping("/update-property") - @Auth(role = "ROLE_ADMIN") - public ApiResponse updateProperty(@Data String data) throws IOException { - Long themeId = objectMapper.readTree(data).get("themeId").asLong(); - Long propertyId = objectMapper.readTree(data).get("propertyId").asLong(); - String value = objectMapper.readTree(data).get("value").asText(); - themeManagerService.updateThemeProperty(themeId, propertyId, value); - - return new ApiResponse(SUCCESS, "Theme updated", themeManagerService.getCurrentTheme()); - } - - /** - * - * @param data - * @return - * @throws IOException - */ - @ApiMapping("/add-theme") - @Auth(role = "ROLE_ADMIN") - public ApiResponse addTheme(@Data String data) throws IOException { - String themeName = objectMapper.readTree(data).get("newTheme").get("name").asText(); - CoreTheme newTheme = coreThemeRepo.create(themeName); - simpMessagingTemplate.convertAndSend("/channel/theme/", new ApiResponse(SUCCESS, newTheme)); - - return new ApiResponse(SUCCESS, "Theme added", newTheme); - } - - /** - * - * @param data - * @return - * @throws IOException - */ - @ApiMapping("/activate-theme") - @Auth(role = "ROLE_ADMIN") - public ApiResponse activateTheme(@Data String data) throws IOException { - Long themeId = objectMapper.readTree(data).get("themeId").asLong(); - themeManagerService.setCurrentTheme(coreThemeRepo.getById(themeId)); - return new ApiResponse(SUCCESS, "Theme activated"); - } -} diff --git a/src/main/java/com/planets/app/controller/UserController.java b/src/main/java/com/planets/app/controller/UserController.java index 32884aa..fe2c646 100644 --- a/src/main/java/com/planets/app/controller/UserController.java +++ b/src/main/java/com/planets/app/controller/UserController.java @@ -1,4 +1,6 @@ /* + * @Author Jeremy Huff + * * UserController.java * * Version: diff --git a/src/main/java/com/planets/app/model/repo/AppUserRepoCustom.java b/src/main/java/com/planets/app/model/repo/AppUserRepoCustom.java index 89b395a..dd385b2 100644 --- a/src/main/java/com/planets/app/model/repo/AppUserRepoCustom.java +++ b/src/main/java/com/planets/app/model/repo/AppUserRepoCustom.java @@ -26,6 +26,8 @@ public interface AppUserRepoCustom { public AppUser create(String email, String firstName, String lastName); + public AppUser create(String email, String firstName, String lastName, String password); + /** * method to delete application user * diff --git a/src/main/java/com/planets/app/model/repo/impl/AppUserRepoImpl.java b/src/main/java/com/planets/app/model/repo/impl/AppUserRepoImpl.java index 8823971..394e35f 100644 --- a/src/main/java/com/planets/app/model/repo/impl/AppUserRepoImpl.java +++ b/src/main/java/com/planets/app/model/repo/impl/AppUserRepoImpl.java @@ -87,4 +87,15 @@ public void delete(AppUser user) { em.remove(em.contains(user) ? user : em.merge(user)); } + @Override + public AppUser create(String email, String firstName, String lastName, + String password) { + + AppUser user = appUserRepo.findByEmail(email); + if (user == null) { + return appUserRepo.save(new AppUser(email, firstName, lastName, password)); + } + return user; + } + } diff --git a/src/main/resources/config/application.properties b/src/main/resources/config/application.properties index d1cfde7..f78406c 100644 --- a/src/main/resources/config/application.properties +++ b/src/main/resources/config/application.properties @@ -35,13 +35,13 @@ server.port: 9000 # Required in framework - JwtUtility auth.security.jwt.secret-key: verysecretsecret -auth.security.jwt-expiration: 120000 +auth.security.jwt-expiration: 12000000 # Required in framework - AuthUtility app.security.secret: verysecretsecret # Required in framework - CoreCorsFilter -app.security.allow-access: http://localhost +app.security.allow-access: http://localhost:8000,http://localhost app.authority.admins: 123456789 diff --git a/src/main/resources/config/banner.txt b/src/main/resources/config/banner.txt index 851c1b9..db32a92 100644 --- a/src/main/resources/config/banner.txt +++ b/src/main/resources/config/banner.txt @@ -1,6 +1,20 @@ - _ __ -| | / /__ ____ __ _____ _____ -| | /| / / _ \/ __ `/ | / / _ \/ ___/ -| |/ |/ / __/ /_/ /| |/ / __/ / -|__/|__/\___/\__,_/ |___/\___/_/ - \ No newline at end of file + ,o88888 + ,o8888888' + ,:o:o:oooo. ,8O88Pd8888" + ,.::.::o:ooooOoOoO. ,oO8O8Pd888'" + ,.:.::o:ooOoOoOO8O8OOo.8OOPd8O8O" + , ..:.::o:ooOoOOOO8OOOOo.FdO8O8" + , ..:.::o:ooOoOO8O888O8O,COCOO" + , . ..:.::o:ooOoOOOO8OOOOCOCO" + . ..:.::o:ooOoOoOO8O8OCCCC"o + . ..:.::o:ooooOoCoCCC"o:o + . ..:.::o:o:,cooooCo"oo:o: + ` . . ..:.:cocoooo"'o:o:::' + .` . ..::ccccoc"'o:o:o:::' + :.:. ,c:cccc"':.:.:.:.:.' + ..:.:"'`::::c:"'..:.:.:.:.:.' + ...:.'.:.::::"' . . . . .' + .. . ....:."' ` . . . '' + . . . ...."' + .. . ."' WEBGL PLANETS + . diff --git a/src/test/java/com/planets/app/controller/AbstractControllerTest.java b/src/test/java/com/planets/app/controller/AbstractControllerTest.java new file mode 100644 index 0000000..c7bee76 --- /dev/null +++ b/src/test/java/com/planets/app/controller/AbstractControllerTest.java @@ -0,0 +1,22 @@ +package com.planets.app.controller; + +import org.mockito.InjectMocks; +import org.mockito.Spy; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.planets.app.WebServerInit; + +import edu.tamu.framework.model.Credentials; +import edu.tamu.framework.util.AuthUtility; +import edu.tamu.framework.util.JwtUtility; + +@WebAppConfiguration +@SpringApplicationConfiguration(classes = { WebServerInit.class }) +public abstract class AbstractControllerTest { + + + +} diff --git a/src/test/java/com/planets/app/controller/AuthControllerTest.java b/src/test/java/com/planets/app/controller/AuthControllerTest.java new file mode 100644 index 0000000..b776ff8 --- /dev/null +++ b/src/test/java/com/planets/app/controller/AuthControllerTest.java @@ -0,0 +1,181 @@ +package com.planets.app.controller; + +import static org.junit.Assert.*; +import static org.mockito.Matchers.any; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.planets.app.model.AppUser; +import com.planets.app.model.repo.AppUserRepo; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.test.util.ReflectionTestUtils; + +import edu.tamu.framework.enums.ApiResponseType; +import edu.tamu.framework.model.ApiResponse; +import edu.tamu.framework.model.Credentials; +import edu.tamu.framework.util.AuthUtility; +import edu.tamu.framework.util.JwtUtility; + +public class AuthControllerTest extends AbstractControllerTest { + + + private Credentials TEST_CREDENTIALS = new Credentials(); + + @Spy + private ObjectMapper objectMapper; + + @Spy @InjectMocks + private AuthUtility authUtility; + + @Spy + private BCryptPasswordEncoder passwordEncoder; + + @Spy @InjectMocks + private JwtUtility jwtUtility; + + private static final String SECRET_PROPERTY_NAME = "secret"; + private static final String SECRET_VALUE = "verysecretsecret"; + + private static final String JWT_SECRET_KEY_PROPERTY_NAME = "secret_key"; + private static final String JWT_SECRET_KEY_VALUE = "verysecretsecret"; + + private static final String JWT_EXPIRATION_PROPERTY_NAME = "expiration"; + private static final Long JWT_EXPIRATION_VALUE = 120000L; + + private static final String[] TEST_USER_1_EMAIL = {"testUser1@domain.tld"}; + private static final String[] TEST_USER_1_FIRST_NAME = {"Test 1"}; + private static final String[] TEST_USER_1_LAST_NAME = {"User 1"}; + private static final String[] TEST_USER_1_PASSWORD = {"iamtestuser1"}; + + private static final String[] TEST_USER_2_EMAIL = {"testUser2@domain.tld"}; + private static final String[] TEST_USER_2_FIRST_NAME = {"Test 2"}; + private static final String[] TEST_USER_2_LAST_NAME = {"User 2"}; + private static final String[] TEST_USER_2_PASSWORD = {"iamtestuser2"}; + + private AppUser TEST_USER_1 = new AppUser(TEST_USER_1_EMAIL[0], TEST_USER_1_FIRST_NAME[0], TEST_USER_1_LAST_NAME[0], TEST_USER_1_PASSWORD[0]); + private AppUser TEST_USER_2 = new AppUser(TEST_USER_2_EMAIL[0], TEST_USER_2_FIRST_NAME[0], TEST_USER_2_LAST_NAME[0], TEST_USER_2_PASSWORD[0]); + + @Mock + private AppUserRepo appUserRepo; + + @InjectMocks + private AuthController authController; + + private static List mockUsers; + + public AppUser findByEmail(String email) { + for(AppUser user : mockUsers) { + if(user.getEmail().equals(email)) { + return user; + } + } + return null; + } + + private AppUser updateUser(AppUser updatedUser) { + for(AppUser user : mockUsers) { + if(user.getEmail().equals(updatedUser.getEmail())) { + user.setEmail(updatedUser.getEmail()); + user.setFirstName(updatedUser.getFirstName()); + user.setLastName(updatedUser.getLastName()); + user.setPassword(updatedUser.getPassword()); + user.setRole(updatedUser.getRole()); + return user; + } + } + return null; + } + + @Before + public void setup() { + + MockitoAnnotations.initMocks(this); + + mockUsers = Arrays.asList(new AppUser[] {TEST_USER_1, TEST_USER_2}); + + ReflectionTestUtils.setField(authUtility, SECRET_PROPERTY_NAME, SECRET_VALUE); + + ReflectionTestUtils.setField(jwtUtility, JWT_SECRET_KEY_PROPERTY_NAME, JWT_SECRET_KEY_VALUE); + + ReflectionTestUtils.setField(jwtUtility, JWT_EXPIRATION_PROPERTY_NAME, JWT_EXPIRATION_VALUE); + + TEST_CREDENTIALS.setFirstName(TEST_USER_1_FIRST_NAME[0]); + TEST_CREDENTIALS.setLastName(TEST_USER_1_LAST_NAME[0]); + TEST_CREDENTIALS.setEmail(TEST_USER_1_EMAIL[0]); + + Mockito.when(appUserRepo.findAll()).thenReturn(mockUsers); + + Mockito.when(appUserRepo.create(any(String.class), any(String.class), any(String.class), any(String.class))).then(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + return appUserRepo.save(new AppUser((String) invocation.getArguments()[0], + (String) invocation.getArguments()[1], + (String) invocation.getArguments()[2], + (String) invocation.getArguments()[3])); + }} + ); + + Mockito.when(appUserRepo.save(any(AppUser.class))).then(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + return updateUser((AppUser) invocation.getArguments()[0]); + }} + ); + + Mockito.when(appUserRepo.findByEmail(any(String.class))).then(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + return findByEmail((String) invocation.getArguments()[0]); + }} + ); + + } + + @Test + public void testLogin() throws Exception { + + testRegister(); + + Map parameters = new HashMap(); + parameters.put("email", TEST_USER_1_EMAIL); + parameters.put("password", TEST_USER_1_PASSWORD); + + ApiResponse response = authController.login(parameters); + + assertEquals(response.getMeta().getMessage(), ApiResponseType.SUCCESS, response.getMeta().getType()); + } + + @Test + public void testRegister() throws Exception { + + Map parameters = new HashMap(); + + parameters.put("email", TEST_USER_1_EMAIL); + parameters.put("password", TEST_USER_1_PASSWORD); + + ApiResponse response = authController.registration(parameters); + + AppUser user = (AppUser) response.getPayload().get("AppUser"); + + assertEquals(ApiResponseType.SUCCESS, response.getMeta().getType()); + + assertEquals(TEST_USER_1_EMAIL[0], user.getEmail()); + assertEquals(true, authUtility.validatePassword(TEST_USER_1_PASSWORD[0], user.getPassword())); + } + +}