aboutsummaryrefslogtreecommitdiff
path: root/juick-server/src/main/java/com/juick/util/UserUtils.java
blob: ddeedbbd2054d7018629afbe709a6ae630c2b149 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.juick.util;

import com.juick.User;
import com.juick.entity.AnonymUser;
import com.juick.server.security.entities.JuickUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Random;

/**
 * Created by aalexeev on 11/14/16.
 */
public class UserUtils {
    private UserUtils() {
        throw new IllegalStateException();
    }

    private static final String ABCDEF = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static String generateHash(final int len) {
        Random rnd = new Random();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            sb.append(ABCDEF.charAt(rnd.nextInt(ABCDEF.length())));
        }
        return sb.toString();
    }

    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    public static Object getPrincipal(final Authentication authentication) {
        return authentication == null ? null : authentication.getPrincipal();
    }

    public static User getCurrentUser() {
        Object principal = getPrincipal(getAuthentication());

        if (principal instanceof JuickUser)
            return ((JuickUser) principal).getUser();

        if (principal instanceof User)
            return (User) principal;

        return AnonymUser.INSTANCE;
    }
}