All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.lsn.spring.auth.controller.UserController Maven / Gradle / Ivy

package io.lsn.spring.auth.controller;

import com.fasterxml.jackson.annotation.JsonView;
import io.lsn.spring.auth.entity.User;
import io.lsn.spring.auth.entity.UserLoginRequest;
import io.lsn.spring.auth.service.UserProvider;
import io.lsn.spring.utilities.configuration.condition.ConditionalOnConfiguration;
import io.lsn.spring.utilities.exception.NotFoundException;
import io.lsn.spring.utilities.json.views.JsonViews;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Patryk Szlagowski 
 */
@ConditionalOnConfiguration(name = "io.lsn.spring.auth", type = ConditionalOnConfiguration.Type.ENDPOINT)
@RestController
@RequestMapping("/api/")
public class UserController {

    @Autowired
    private UserProvider provider;

    @RequestMapping(value = "/user/logout", method = {RequestMethod.GET})
    public ResponseEntity logout(HttpServletRequest request) throws Exception {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth.getPrincipal() instanceof String) {
            return new ResponseEntity<>(HttpStatus.OK);
        }
        User logged = (User) auth.getPrincipal();
        provider.terminateApiToken(logged);
        SecurityContextHolder.clearContext();
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @JsonView(JsonViews.Public.class)
    @RequestMapping(value = "/user/login", method = {RequestMethod.POST})
    public ResponseEntity auth(@RequestBody UserLoginRequest login) throws Exception {
        User user;
        try {
            user = provider.findByUsername(login.getUsername());
        } catch (NotFoundException e) {
            throw new BadCredentialsException("unknown user");
        }
        provider.authenticate(user, login.getPassword());

        return new ResponseEntity<>(user, HttpStatus.OK);
    }

    @JsonView(JsonViews.Public.class)
    @RequestMapping(value = "/secured/user", method = RequestMethod.GET)
    public ResponseEntity getLogged() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        return new ResponseEntity(auth.getPrincipal(), HttpStatus.OK);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy