aboutsummaryrefslogtreecommitdiff
path: root/juick-server/src/main/java/com/juick/util/UserUtils.java
blob: 372dd502e1c9fa29b70054ae0cc6961f7abef3c0 (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
package com.juick.util;

import java.security.Principal;
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 boolean checkUserNameValid(final String uname) {
        return uname != null && uname.length() >= 2 && uname.length() <= 16 && uname.matches("[a-zA-Z0-9\\-]+");
    }

    public static String getUsername(final Principal principal, final String defaultUsername) {
        return principal == null ? defaultUsername : principal.getName();
    }
}