Passed
Push — dev ( 970466...ad4cc5 )
by Konstantin
04:23
created

show(Integer)   A

Complexity

Conditions 3

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 13
rs 9.75
cc 3
1
package easytests.api.v1.controllers;
2
3
import easytests.api.v1.exceptions.*;
4
import easytests.api.v1.mappers.UsersMapper;
5
import easytests.api.v1.models.Identity;
6
import easytests.api.v1.models.User;
7
import easytests.auth.services.SessionServiceInterface;
8
import easytests.core.models.UserModel;
9
import easytests.core.models.UserModelInterface;
10
import easytests.core.options.UsersOptionsInterface;
11
import easytests.core.options.builder.UsersOptionsBuilderInterface;
12
import easytests.core.services.UsersServiceInterface;
13
import java.util.List;
14
import java.util.stream.Collectors;
15
import org.springframework.beans.factory.annotation.Autowired;
16
import org.springframework.beans.factory.annotation.Qualifier;
17
import org.springframework.http.HttpStatus;
18
import org.springframework.web.bind.annotation.*;
19
20
21
/**
22
 * @author SvetlanaTselikova
23
 */
24
@RestController("UsersControllerV1")
25
@SuppressWarnings("checkstyle:MultipleStringLiterals")
26
@RequestMapping("/v1/users")
27
public class UsersController {
28
29
    @Autowired
30
    protected UsersServiceInterface usersService;
31
32
    @Autowired
33
    private UsersOptionsBuilderInterface usersOptionsBuilder;
34
35
    @Autowired
36
    private SessionServiceInterface sessionService;
37
38
    @Autowired
39
    @Qualifier("UsersMapperV1")
40
    private UsersMapper usersMapper;
41
42
    private Boolean isAdmin() {
43
        if (!this.sessionService.isUser()) {
44
            return false;
45
        }
46
        return this.sessionService.getUserModel().getIsAdmin();
47
    }
48
49
    @GetMapping("")
50
    public List<User> list() throws ForbiddenException {
51
        if (!this.isAdmin()) {
52
            throw new ForbiddenException();
53
        }
54
        final List<UserModelInterface> usersModels = this.usersService.findAll();
55
56
        return usersModels
57
                .stream()
58
                .map(model -> this.usersMapper.map(model, User.class))
59
                .collect(Collectors.toList());
60
    }
61
62
    @PostMapping("")
63
    @ResponseStatus(HttpStatus.CREATED)
64
    public Identity create(@RequestBody User user) throws BadRequestException, ForbiddenException {
65
        if (!this.isAdmin()) {
66
            throw new ForbiddenException();
67
        }
68
        if (user.getId() != null) {
69
            throw new IdentifiedModelException();
70
        }
71
        if (this.usersService.findByEmail(user.getEmail()) != null) {
72
            throw new BadRequestException("This email already exist.");
73
        }
74
75
        final UserModelInterface userModel = this.usersMapper.map(user, UserModel.class);
76
77
        userModel.setPassword(passgenerator(6));
78
79
        this.usersService.save(userModel);
80
81
        return this.usersMapper.map(userModel, Identity.class);
82
    }
83
84
    /**
85
     * update
86
     */
87
    @GetMapping("/{userId}")
88
    public User show(@PathVariable Integer userId) throws NotFoundException, ForbiddenException {
89
        final UserModelInterface userModel = this.usersService.find(userId);
90
91
        if (!this.isAdmin()) {
92
            throw new ForbiddenException();
93
        }
94
95
        if (userModel == null) {
96
            throw new NotFoundException();
97
        }
98
99
        return this.usersMapper.map(userModel, User.class);
100
    }
101
102
    @PutMapping("")
103
    public void update(@RequestBody User user) throws Exception {
0 ignored issues
show
Best Practice introduced by
Dedicated exceptions should be preferred over throwing the generic Exception.
Loading history...
104
        if (!this.isAdmin()) {
105
            throw new ForbiddenException();
106
        }
107
108
        if (user.getId() == null) {
109
            throw new UnidentifiedModelException();
110
        }
111
112
        final UserModelInterface userModel = this.usersService.find(user.getId());
113
114
        if (userModel == null) {
115
            throw new NotFoundException();
116
        }
117
118
        this.usersMapper.map(user, userModel);
119
120
        this.usersService.save(userModel);
121
    }
122
123
    @DeleteMapping("/{userId}")
124
    public void delete(@PathVariable Integer userId) throws NotFoundException, ForbiddenException {
125
        if (!this.isAdmin()) {
126
            throw new ForbiddenException();
127
        }
128
129
        final UsersOptionsInterface usersOptions = this.usersOptionsBuilder.forDelete();
130
        final UserModelInterface userModel = this.usersService.find(userId, usersOptions);
131
132
        if (userModel == null) {
133
            throw new NotFoundException();
134
        }
135
136
        this.usersService.delete(userModel, usersOptions);
137
    }
138
139
    @GetMapping("/me")
140
    public User showme() throws ForbiddenException {
141
142
        if (!this.sessionService.isUser()) {
143
            throw new ForbiddenException();
144
        }
145
        final UserModelInterface userModel = this.sessionService.getUserModel();
146
        return this.usersMapper.map(userModel, User.class);
147
    }
148
149
    private String passgenerator(int n) {
150
        final String dict = "qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM";
151
        String pass = "";
152
        for (int i = 0; i < n; i++) {
153
            pass = pass + (dict.charAt(0 + (int) (Math.random() * dict.length())));
0 ignored issues
show
Performance introduced by
String concatenation with + is inefficient. Doing so in a loop may incur a significant performance penalty. Consider using a StringBuilder instead
Loading history...
introduced by
Use "java.util.Random.nextInt()" instead.
Loading history...
154
        }
155
        return pass;
156
    }
157
}
158