Search in sources :

Example 1 with TokenModel

use of com.infiniteautomation.mango.rest.v2.model.jwt.TokenModel in project ma-modules-public by infiniteautomation.

the class AuthenticationTokenRestController method createToken.

@ApiOperation(value = "Create auth token", notes = "Creates an authentication token for the current user or for the username specified (admin only)")
@RequestMapping(path = "/create", method = RequestMethod.POST)
@PreAuthorize("isAuthenticated() and isPasswordAuthenticated()")
public ResponseEntity<TokenModel> createToken(@RequestBody CreateTokenRequest requestBody, @AuthenticationPrincipal User currentUser) {
    Date expiry = requestBody.getExpiry();
    String username = requestBody.getUsername();
    User user = currentUser;
    if (username != null && !username.equals(currentUser.getUsername())) {
        if (!currentUser.isAdmin()) {
            throw new AccessDeniedException(new TranslatableMessage("rest.error.onlyAdminsCanCreateTokens"));
        }
        user = UserDao.instance.getUser(username);
        if (user == null) {
            throw new BadRequestException(new TranslatableMessage("rest.error.unknownUser", username));
        }
    }
    String token = tokenAuthService.generateToken(user, expiry);
    return new ResponseEntity<>(new TokenModel(token), HttpStatus.CREATED);
}
Also used : AccessDeniedException(com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException) ResponseEntity(org.springframework.http.ResponseEntity) User(com.serotonin.m2m2.vo.User) BadRequestException(com.infiniteautomation.mango.rest.v2.exception.BadRequestException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) Date(java.util.Date) TokenModel(com.infiniteautomation.mango.rest.v2.model.jwt.TokenModel) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

AccessDeniedException (com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException)1 BadRequestException (com.infiniteautomation.mango.rest.v2.exception.BadRequestException)1 TokenModel (com.infiniteautomation.mango.rest.v2.model.jwt.TokenModel)1 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)1 User (com.serotonin.m2m2.vo.User)1 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)1 Date (java.util.Date)1 ResponseEntity (org.springframework.http.ResponseEntity)1 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)1 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)1