UsersController.java

/*
 * +====================================================================+
 * |         Copyright (C) 2015 Rochester Institute of Technology,      |
 * |            103 Lomb Memorial Drive, Rochester, NY - 14623          |
 * |                        All Rights Reserved.                        |
 * +====================================================================+
 *   FILENAME
 *    UsersController.java
 *
 *   AUTHOR
 *    @author Khanh Ho (kchisd at rit.edu)
 *
 * =====================================================================
 */

package edu.rit.coopeval.controller.rest;

import com.fasterxml.jackson.annotation.JsonView;
import edu.rit.coopeval.dao.UserRepository;
import edu.rit.coopeval.model.User;
import edu.rit.coopeval.model.UserRole;
import edu.rit.coopeval.security.SecurityUser;
import edu.rit.coopeval.viewmodel.JsonViewer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

/**
 * Controller for endpoints /api/users
 */
@RestController
@RequestMapping(path = "api/users", produces = "application/json")
public class UsersController {

    @Autowired
    private UserRepository userRepo;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * Create a new user.
     *
     * @param user the user
     *
     * @return response message indicating whether the operation was successful
     */
    @RequestMapping(method = RequestMethod.POST)
    @PreAuthorize("hasAuthority('Administrator')")
    public String createUser(@RequestBody User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        for (UserRole r : user.getRoles()) {
            r.setUser(user);
        }

        userRepo.save(user);
        return "{\"OK\"}";
    }

    /**
     * GET the currently logged in user.
     *
     * @param sUser the current principal
     *
     * @return detailed info about the user
     */
    @JsonView(JsonViewer.UserDetails.class)
    @RequestMapping(path = "me", method = RequestMethod.GET)
    public User getCurrentUser(@AuthenticationPrincipal SecurityUser sUser) {
        User user = sUser.user();
        return userRepo.findWithDetailsByUsername(user.getUsername());
    }
}