LoginRepository.java 17.1 KB
Newer Older
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 

M
MaxKey 已提交
18
package org.maxkey.persistence.repository;
19 20 21 22 23 24 25 26

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

M
v 3.3.0  
MaxKey 已提交
27
import org.maxkey.constants.ConstsStatus;
M
MaxKey 已提交
28 29
import org.maxkey.entity.Groups;
import org.maxkey.entity.UserInfo;
30 31 32 33 34 35 36 37
import org.maxkey.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

M
MaxKey 已提交
38 39
public class LoginRepository {
    private static Logger _logger = LoggerFactory.getLogger(LoginRepository.class);
40

M
MaxKey 已提交
41
    private static final String LOCK_USER_UPDATE_STATEMENT = "update mxk_userinfo set islocked = ?  , unlocktime = ? where id = ?";
42

M
MaxKey 已提交
43
    private static final String UNLOCK_USER_UPDATE_STATEMENT = "update mxk_userinfo set islocked = ? , unlocktime = ? where id = ?";
44

M
MaxKey 已提交
45
    private static final String BADPASSWORDCOUNT_UPDATE_STATEMENT = "update mxk_userinfo set badpasswordcount = ? , badpasswordtime = ?  where id = ?";
46

M
MaxKey 已提交
47
    private static final String BADPASSWORDCOUNT_RESET_UPDATE_STATEMENT = "update mxk_userinfo set badpasswordcount = ? , islocked = ? ,unlocktime = ?  where id = ?";
48

M
MaxKey 已提交
49 50
    private static final String LOGIN_USERINFO_UPDATE_STATEMENT = "update mxk_userinfo set lastlogintime = ?  , lastloginip = ? , logincount = ?, online = "
            + UserInfo.ONLINE.ONLINE + "  where id = ?";
51

M
MaxKey 已提交
52 53
    private static final String LOGOUT_USERINFO_UPDATE_STATEMENT = "update mxk_userinfo set lastlogofftime = ? , online = "
            + UserInfo.ONLINE.OFFLINE + "  where id = ?";
54

M
MaxKey 已提交
55
    private static final String GROUPS_SELECT_STATEMENT = "select distinct g.id,g.name from mxk_userinfo u,mxk_groups g,mxk_group_member gm where u.id = ?  and u.id=gm.memberid and gm.groupid=g.id ";
56

M
MaxKey 已提交
57
    private static final String DEFAULT_USERINFO_SELECT_STATEMENT = "select * from  mxk_userinfo where username = ? ";
58
    
M
MaxKey 已提交
59
    private static final String DEFAULT_USERINFO_SELECT_STATEMENT_USERNAME_MOBILE = "select * from  mxk_userinfo where (username = ? or mobile = ?)";
M
MaxKey 已提交
60
    
M
MaxKey 已提交
61
    private static final String DEFAULT_USERINFO_SELECT_STATEMENT_USERNAME_MOBILE_EMAIL = "select * from  mxk_userinfo where (username = ? or mobile = ? or email = ?) ";
M
MaxKey 已提交
62
    
M
MaxKey 已提交
63
    private static final String DEFAULT_MYAPPS_SELECT_STATEMENT = "select distinct app.id,app.name from mxk_apps app,mxk_group_privileges gp,mxk_groups g  where app.id=gp.appid and gp.groupid=g.id and g.id in(%s)";
64
    
65 66
    protected JdbcTemplate jdbcTemplate;
    
M
MaxKey 已提交
67 68 69
    /**
     * 1 (USERNAME)  2 (USERNAME | MOBILE) 3 (USERNAME | MOBILE | EMAIL)
     */
M
MaxKey 已提交
70
    public  static  int LOGIN_ATTRIBUTE_TYPE = 2;
M
MaxKey 已提交
71
    
M
MaxKey 已提交
72
    public LoginRepository(){
73 74 75
        
    }
    
M
MaxKey 已提交
76
    public LoginRepository(JdbcTemplate jdbcTemplate){
77 78 79
        this.jdbcTemplate=jdbcTemplate;
    }
    
M
MaxKey 已提交
80
    public UserInfo find(String username, String password) {
M
MaxKey 已提交
81 82
        List<UserInfo> listUserInfo = null ;
        if( LOGIN_ATTRIBUTE_TYPE == 1) {
M
MaxKey 已提交
83
        	listUserInfo = findByUsername(username,password);
M
MaxKey 已提交
84
        }else if( LOGIN_ATTRIBUTE_TYPE == 2) {
M
MaxKey 已提交
85
        	 listUserInfo = findByUsernameOrMobile(username,password);
M
MaxKey 已提交
86
        }else if( LOGIN_ATTRIBUTE_TYPE == 3) {
M
MaxKey 已提交
87
        	 listUserInfo = findByUsernameOrMobileOrEmail(username,password);
M
MaxKey 已提交
88 89
        }
        
90 91 92 93 94 95 96 97
        UserInfo userInfo = null;
        if (listUserInfo != null && listUserInfo.size() > 0) {
            userInfo = listUserInfo.get(0);
        }
        _logger.debug("load UserInfo : " + userInfo);
        return userInfo;
    }
    
M
MaxKey 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
    public List<UserInfo> findByUsername(String username, String password) {
    	return jdbcTemplate.query(
    			DEFAULT_USERINFO_SELECT_STATEMENT, 
    			new UserInfoRowMapper(),
    			username
    		);
    }
    
    public List<UserInfo> findByUsernameOrMobile(String username, String password) {
    	return jdbcTemplate.query(
			 	DEFAULT_USERINFO_SELECT_STATEMENT_USERNAME_MOBILE, 
    			new UserInfoRowMapper(),
    			username,username
    		);
    }
    
    public List<UserInfo> findByUsernameOrMobileOrEmail(String username, String password) {
    	return jdbcTemplate.query(
			 	DEFAULT_USERINFO_SELECT_STATEMENT_USERNAME_MOBILE_EMAIL, 
    			new UserInfoRowMapper(),
    			username,username,username
    		);
    }
121 122 123 124 125 126 127
    

    /**
     * 閿佸畾鐢ㄦ埛锛歩slock锛�1 鐢ㄦ埛瑙i攣 2 鐢ㄦ埛閿佸畾
     * 
     * @param userInfo
     */
M
MaxKey 已提交
128
    public void updateLock(UserInfo userInfo) {
129 130 131
        try {
            if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) {
                jdbcTemplate.update(LOCK_USER_UPDATE_STATEMENT,
M
v 3.3.0  
MaxKey 已提交
132
                        new Object[] { ConstsStatus.LOCK, new Date(), userInfo.getId() },
133
                        new int[] { Types.VARCHAR, Types.TIMESTAMP, Types.VARCHAR });
M
v 3.3.0  
MaxKey 已提交
134
                userInfo.setIsLocked(ConstsStatus.LOCK);
135 136
            }
        } catch (Exception e) {
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
137
            _logger.error("lockUser Exception",e);
138 139 140 141 142 143 144 145
        }
    }

    /**
     * 閿佸畾鐢ㄦ埛锛歩slock锛�1 鐢ㄦ埛瑙i攣 2 鐢ㄦ埛閿佸畾
     * 
     * @param userInfo
     */
M
MaxKey 已提交
146
    public void updateUnlock(UserInfo userInfo) {
147 148 149
        try {
            if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) {
                jdbcTemplate.update(UNLOCK_USER_UPDATE_STATEMENT,
M
v 3.3.0  
MaxKey 已提交
150
                        new Object[] { ConstsStatus.ACTIVE, new Date(), userInfo.getId() },
151
                        new int[] { Types.VARCHAR, Types.TIMESTAMP, Types.VARCHAR });
M
v 3.3.0  
MaxKey 已提交
152
                userInfo.setIsLocked(ConstsStatus.ACTIVE);
153 154
            }
        } catch (Exception e) {
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
155
            _logger.error("unlockUser Exception",e);
156 157 158 159 160 161 162 163
        }
    }

    /**
    * reset BadPasswordCount And Lockout
     * 
     * @param userInfo
     */
M
MaxKey 已提交
164
    public void updateLockout(UserInfo userInfo) {
165 166 167
        try {
            if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) {
                jdbcTemplate.update(BADPASSWORDCOUNT_RESET_UPDATE_STATEMENT,
M
v 3.3.0  
MaxKey 已提交
168
                        new Object[] { 0, ConstsStatus.ACTIVE, new Date(), userInfo.getId() },
169
                        new int[] { Types.INTEGER, Types.INTEGER, Types.TIMESTAMP, Types.VARCHAR });
M
v 3.3.0  
MaxKey 已提交
170
                userInfo.setIsLocked(ConstsStatus.ACTIVE);
171 172
            }
        } catch (Exception e) {
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
173
            _logger.error("resetBadPasswordCountAndLockout Exception",e);
174 175 176 177 178 179 180 181
        }
    }

    /**
     * if login password is error ,BadPasswordCount++ and set bad date
     * 
     * @param userInfo
     */
M
MaxKey 已提交
182
    public void updateBadPasswordCount(UserInfo userInfo) {
183 184 185 186 187 188 189 190 191 192 193 194 195 196
        try {
            if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) {
                int badPasswordCount = userInfo.getBadPasswordCount() + 1;
                userInfo.setBadPasswordCount(badPasswordCount);
                jdbcTemplate.update(BADPASSWORDCOUNT_UPDATE_STATEMENT,
                        new Object[] { badPasswordCount, new Date(), userInfo.getId() },
                        new int[] { Types.INTEGER, Types.TIMESTAMP, Types.VARCHAR });
            }
        } catch (Exception e) {
            e.printStackTrace();
            _logger.error(e.getMessage());
        }
    }
    
197 198 199 200 201 202 203 204 205 206
    public ArrayList<GrantedAuthority> queryAuthorizedApps(ArrayList<GrantedAuthority> grantedAuthoritys) {
        String grantedAuthorityString="'ROLE_ALL_USER'";
        for(GrantedAuthority grantedAuthority : grantedAuthoritys) {
            grantedAuthorityString += ",'"+ grantedAuthority.getAuthority()+"'";
        }
        
        ArrayList<GrantedAuthority> listAuthorizedApps = (ArrayList<GrantedAuthority>) jdbcTemplate.query(
                String.format(DEFAULT_MYAPPS_SELECT_STATEMENT, grantedAuthorityString), 
                new RowMapper<GrantedAuthority>() {
            public GrantedAuthority mapRow(ResultSet rs, int rowNum) throws SQLException {
M
MaxKey 已提交
207
                return new SimpleGrantedAuthority(rs.getString("id"));
208 209 210 211 212 213 214
            }
        });

        _logger.debug("list Authorized Apps  " + listAuthorizedApps);
        return listAuthorizedApps;
    }
    
215 216 217
    public List<Groups> queryGroups(UserInfo userInfo) {
        List<Groups> listGroups = jdbcTemplate.query(GROUPS_SELECT_STATEMENT, new RowMapper<Groups>() {
            public Groups mapRow(ResultSet rs, int rowNum) throws SQLException {
M
MaxKey 已提交
218
                Groups group = new Groups(rs.getString("id"), rs.getString("name"), 0);
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237

                return group;
            }
        }, userInfo.getId());

        _logger.debug("list Groups  " + listGroups);
        return listGroups;
    }

    /**
     * grant Authority by userinfo
     * 
     * @param userInfo
     * @return ArrayList<GrantedAuthority>
     */
    public ArrayList<GrantedAuthority> grantAuthority(UserInfo userInfo) {
        // query roles for user
        List<Groups> listGroups = queryGroups(userInfo);

238
        //set default roles
239 240
        ArrayList<GrantedAuthority> grantedAuthority = new ArrayList<GrantedAuthority>();
        grantedAuthority.add(new SimpleGrantedAuthority("ROLE_USER"));
241 242
        grantedAuthority.add(new SimpleGrantedAuthority("ROLE_ORDINARY_USER"));
        grantedAuthority.add(new SimpleGrantedAuthority("ROLE_ALL_USER"));
243 244 245 246 247 248 249 250 251
        for (Groups group : listGroups) {
            grantedAuthority.add(new SimpleGrantedAuthority(group.getId()));
        }
        _logger.debug("Authority : " + grantedAuthority);

        return grantedAuthority;
    }
    
    
M
MaxKey 已提交
252
    public void updateLastLogin(UserInfo userInfo) {
253
        jdbcTemplate.update(LOGIN_USERINFO_UPDATE_STATEMENT,
M
MaxKey 已提交
254 255 256 257 258 259
                new Object[] { 
                				userInfo.getLastLoginTime(), 
                				userInfo.getLastLoginIp(), 
                				userInfo.getLoginCount() + 1, 
                				userInfo.getId() 
                			},
M
MaxKey 已提交
260
                new int[] { Types.VARCHAR, Types.VARCHAR, Types.INTEGER, Types.VARCHAR });
261 262
    }
    
M
MaxKey 已提交
263 264 265 266
    public void updateLastLogoff(UserInfo userInfo) {
        jdbcTemplate.update(	LOGOUT_USERINFO_UPDATE_STATEMENT, 
        		new Object[] { 	userInfo.getLastLogoffTime(), userInfo.getId() },
                new int[] { 	Types.VARCHAR, Types.VARCHAR });
267
    }
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
268 269 270 271 272 273
    
    public class UserInfoRowMapper implements RowMapper<UserInfo> {
        @Override
        public UserInfo mapRow(ResultSet rs, int rowNum) throws SQLException {

            UserInfo userInfo = new UserInfo();
M
MaxKey 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
            userInfo.setId(rs.getString("id"));
            userInfo.setUsername(rs.getString("username"));
            userInfo.setPassword(rs.getString("password"));
            userInfo.setSharedSecret(rs.getString("sharedsecret"));
            userInfo.setSharedCounter(rs.getString("sharedcounter"));
            userInfo.setDecipherable(rs.getString("decipherable"));
            userInfo.setWindowsAccount(rs.getString("windowsaccount"));
            userInfo.setUserType(rs.getString("usertype"));

            userInfo.setDisplayName(rs.getString("displayname"));
            userInfo.setNickName(rs.getString("nickname"));
            userInfo.setNameZhSpell(rs.getString("namezhspell"));// nameZHSpell
            userInfo.setNameZhShortSpell(rs.getString("namezhshortspell"));// nameZHSpell
            userInfo.setGivenName(rs.getString("givenname"));
            userInfo.setMiddleName(rs.getString("middlename"));
            userInfo.setFamilyName(rs.getString("familyname"));
            userInfo.setHonorificPrefix(rs.getString("honorificprefix"));
            userInfo.setHonorificSuffix(rs.getString("honorificsuffix"));
            userInfo.setFormattedName(rs.getString("formattedname"));

            userInfo.setGender(rs.getInt("gender"));
            userInfo.setBirthDate(rs.getString("birthdate"));
            userInfo.setPicture(rs.getBytes("picture"));
            userInfo.setMarried(rs.getInt("married"));
            userInfo.setIdType(rs.getInt("idtype"));
            userInfo.setIdCardNo(rs.getString("idcardno"));
            userInfo.setWebSite(rs.getString("website"));

            userInfo.setAuthnType(rs.getInt("authntype"));
            userInfo.setMobile(rs.getString("mobile"));
            userInfo.setMobileVerified(rs.getInt("mobileverified"));
            userInfo.setEmail(rs.getString("email"));
            userInfo.setEmailVerified(rs.getInt("emailverified"));
            userInfo.setPasswordQuestion(rs.getString("passwordquestion"));
            userInfo.setPasswordAnswer(rs.getString("passwordanswer"));

            userInfo.setAppLoginAuthnType(rs.getInt("apploginauthntype"));
            userInfo.setAppLoginPassword(rs.getString("apploginpassword"));
            userInfo.setProtectedApps(rs.getString("protectedapps"));

            userInfo.setPasswordLastSetTime(rs.getString("passwordlastsettime"));
            userInfo.setPasswordSetType(rs.getInt("passwordsettype"));
            userInfo.setBadPasswordCount(rs.getInt("badpasswordcount"));
            userInfo.setBadPasswordTime(rs.getString("badpasswordtime"));
            userInfo.setUnLockTime(rs.getString("unlocktime"));
            userInfo.setIsLocked(rs.getInt("islocked"));
            userInfo.setLastLoginTime(rs.getString("lastlogintime"));
            userInfo.setLastLoginIp(rs.getString("lastloginip"));
            userInfo.setLastLogoffTime(rs.getString("lastlogofftime"));
            userInfo.setLoginCount(rs.getInt("logincount"));
M
MaxKey 已提交
324 325
            userInfo.setRegionHistory(rs.getString("regionhistory"));
            userInfo.setPasswordHistory(rs.getString("passwordhistory"));
M
MaxKey 已提交
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378

            userInfo.setTimeZone(rs.getString("timezone"));
            userInfo.setLocale(rs.getString("locale"));
            userInfo.setPreferredLanguage(rs.getString("preferredlanguage"));

            userInfo.setWorkEmail(rs.getString("workemail"));
            userInfo.setWorkPhoneNumber(rs.getString("workphonenumber"));
            userInfo.setWorkCountry(rs.getString("workcountry"));
            userInfo.setWorkRegion(rs.getString("workregion"));
            userInfo.setWorkLocality(rs.getString("worklocality"));
            userInfo.setWorkStreetAddress(rs.getString("workstreetaddress"));
            userInfo.setWorkAddressFormatted(rs.getString("workaddressformatted"));
            userInfo.setWorkPostalCode(rs.getString("workpostalcode"));
            userInfo.setWorkFax(rs.getString("workfax"));

            userInfo.setHomeEmail(rs.getString("homeemail"));
            userInfo.setHomePhoneNumber(rs.getString("homephonenumber"));
            userInfo.setHomeCountry(rs.getString("homecountry"));
            userInfo.setHomeRegion(rs.getString("homeregion"));
            userInfo.setHomeLocality(rs.getString("homelocality"));
            userInfo.setHomeStreetAddress(rs.getString("homestreetaddress"));
            userInfo.setHomeAddressFormatted(rs.getString("homeaddressformatted"));
            userInfo.setHomePostalCode(rs.getString("homepostalcode"));
            userInfo.setHomeFax(rs.getString("homefax"));

            userInfo.setEmployeeNumber(rs.getString("employeenumber"));
            userInfo.setDivision(rs.getString("division"));
            userInfo.setCostCenter(rs.getString("costcenter"));
            userInfo.setOrganization(rs.getString("organization"));
            userInfo.setDepartmentId(rs.getString("departmentid"));
            userInfo.setDepartment(rs.getString("department"));
            userInfo.setJobTitle(rs.getString("jobtitle"));
            userInfo.setJobLevel(rs.getString("joblevel"));
            userInfo.setManagerId(rs.getString("managerid"));
            userInfo.setManager(rs.getString("manager"));
            userInfo.setAssistantId(rs.getString("assistantid"));
            userInfo.setAssistant(rs.getString("assistant"));
            userInfo.setEntryDate(rs.getString("entrydate"));//
            userInfo.setQuitDate(rs.getString("quitdate"));
            userInfo.setStartWorkDate(rs.getString("startworkdate"));// STARTWORKDATE

            userInfo.setExtraAttribute(rs.getString("extraattribute"));

            userInfo.setCreatedBy(rs.getString("createdby"));
            userInfo.setCreatedDate(rs.getString("createddate"));
            userInfo.setModifiedBy(rs.getString("modifiedby"));
            userInfo.setModifiedDate(rs.getString("modifieddate"));

            userInfo.setStatus(rs.getInt("status"));
            userInfo.setGridList(rs.getInt("gridlist"));
            userInfo.setDescription(rs.getString("description"));
            userInfo.setTheme(rs.getString("theme"));
            userInfo.setInstId(rs.getString("instid"));
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
379 380 381 382 383 384 385
            if (userInfo.getTheme() == null || userInfo.getTheme().equalsIgnoreCase("")) {
                userInfo.setTheme("default");
            }
            
            return userInfo;
        }
    }
386
}
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
387 388