提交 cd9fd48e authored 作者: renjiancai's avatar renjiancai

--no commit message

上级 51b6a209
......@@ -122,6 +122,11 @@
<artifactId>scala-library</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
</dependencies>
......
package com.zrqx.core.enums;
import java.util.HashMap;
import java.util.stream.Stream;
import com.zrqx.core.enums.interfaces.EnumsInterface;
/**
* 0:测试环境
* 1:生产环境
* @author lpf
* @date 2019年3月22日上午10:04:17
*/
public enum EnvironmentEnum implements EnumsInterface<String>{
/** 测试环境 */
TEST("0","测试环境"),
/** 生产环境 */
PRODUCT("1","生产环境");
private final String code;
private final String name;
private static final HashMap<String,String> MAP = new HashMap<String,String>();
static {
stream().forEach(e -> {
MAP.put(e.code, e.name);
});
}
/**
* @return
* @author lpf
* @date: 2019年3月18日 下午5:05:16
*/
public static Stream<EnvironmentEnum> stream(){
return Stream.of(values());
}
private EnvironmentEnum(String code, String name) {
this.code = code;
this.name = name;
}
/**
* 判断名称是否有效
* @param name
* @return
* @author lpf
* @date: 2018年6月11日 下午6:30:16
*/
public static boolean isExist(String code) {
return stream().anyMatch(e -> e.code.equals(code));
}
/**
* 通过ID获取中文名称
* @param code
* @return
*/
public static String getName(String code) {
return stream().filter(e -> e.code.equals(code)).findFirst().map(e -> e.name).orElse(null);
}
@Override
public String getCode() {
return code;
}
@Override
public String getName() {
return name;
}
public static HashMap<String, String> getMap() {
return MAP;
}
}
package com.zrqx.core.enums.env;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import com.zrqx.core.enums.EnvironmentEnum;
import com.zrqx.core.enums.interfaces.EnumsBindBean;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spring.web.plugins.Docket;
/**
* {@link ConfigServerParams}
* 服务环境绑定的操作
* @author lpf
* @date 2019年3月22日上午11:34:19
*/
public interface EnvironmentInterface extends EnumsBindBean<EnvironmentEnum> {
/**
* swaager-ui对象
* @param info
* @return
* @author lpf
* @date: 2019年3月22日 下午1:42:20
*/
Docket createRestApi(ApiInfo info);
/**
* sql异常处理方案 测试环境需要返回出去,生产环境sql异常不能返回出去。
* @param request
* @param e
* @return
* @author lpf
* @date: 2019年10月29日 上午11:48:40
*/
String handlerException(HttpServletRequest request, SQLException e);
/**
* 生成样书申请编码
* 测试环境: ZRQX + YS + 2随机字母 + yyyyMMddHHmmssSSSS
* 生产环境: YS + 2随机字母 + yyyyMMddHHmmssSSSS
* @return
* @author lpf
* @date: 2019年5月15日 下午3:27:13
*/
String createSampleBookApplyCode();
/**
* 生成订单号
* Z + 2随机字母 + yyyyMMddHHmmssSSSS
* @return
* @author lpf
* @date: 2019年8月7日 上午9:47:38
*/
String createOrderCode();
/**
* 生成用户名
* 系统自动生成用户名(4-10位,字母和数字组合,前两位字母)
* 测试环境: Z + 两位字母 + (2-8)位数字
* 生产环境: 两位字母 + (2-8)位数字
* @return
*/
String createAccount();
}
package com.zrqx.core.enums.env.impl;
import java.util.Random;
import java.util.function.Consumer;
import com.zrqx.core.enums.env.EnvironmentInterface;
import com.zrqx.core.util.datatype.StringUtil;
/**
*
* @author lpf
* @date 2020-07-01 13:52
*/
public abstract class AbstractEnvironment implements EnvironmentInterface {
@Override
public String createSampleBookApplyCode() {
return this.initRandomOrderCode(b -> b.append("YS"));
}
@Override
public String createOrderCode() {
return this.initRandomOrderCode(b -> b.append(StringUtil.getRandomEnSign(1,2,0)));
}
@Override
public String createAccount() {
return this.initRandomOrderCode(b -> {
b.append(StringUtil.getRandomEnSign(1,2,0));
Integer num = new Random().nextInt(6) + 2;
b.append(StringUtil.getRandomNumber(num));
});
}
/**
* 基础生成编码规则
* @return
* @author ydm
* @date: 2018年8月13日 下午2:31:44
*/
protected String initRandomOrderCode(Consumer<StringBuffer> before) {
Consumer<StringBuffer> first = this :: beforeCreateCode;
Consumer<StringBuffer> joinConsumer = first.andThen(before);
StringBuffer result = new StringBuffer();
joinConsumer.accept(result);
return result.toString();
}
/**
* 创建编码之前执行程序, 返回值用于拼接到编码上(返回值+创建编码)
* @param code 编码
* @return
* @author lpf
* @date: 2019年5月15日 下午3:31:18
*/
protected abstract void beforeCreateCode(StringBuffer code);
}
package com.zrqx.core.enums.env.impl;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.zrqx.core.enums.EnvironmentEnum;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/**
* 生产环境绑定操作
* @author lpf
* @date 2019年3月22日上午11:40:41
*/
public class ProductEnvironmentImpl extends AbstractEnvironment{
@Override
public List<EnvironmentEnum> getEnums() {
return Arrays.asList(EnvironmentEnum.PRODUCT);
}
@Override
public Docket createRestApi(ApiInfo info) {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(info)
.select()
//为当前包路径 不存在的包路径
.apis(RequestHandlerSelectors.basePackage("com.zrqx.prod"))
.paths(PathSelectors.any())
.build();
}
@Override
protected void beforeCreateCode(StringBuffer code) {
}
@Override
public String handlerException(HttpServletRequest request, SQLException e) {
return null;
}
}
package com.zrqx.core.enums.env.impl;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.zrqx.core.util.datatype.StringUtil;
import com.zrqx.core.util.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zrqx.core.enums.EnvironmentEnum;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/**
* 测试环境操作
* @author lpf
* @date 2019年3月22日上午11:35:54
*/
public class TestEnvironmentImpl extends AbstractEnvironment {
private static final Logger logger = LoggerFactory.getLogger(TestEnvironmentImpl.class);
@Override
public List<EnvironmentEnum> getEnums() {
return Arrays.asList(EnvironmentEnum.TEST);
}
@Override
public Docket createRestApi(ApiInfo info) {
//添加head参数start
ParameterBuilder tokenPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<Parameter>();
tokenPar.name("y-token").description("令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
ParameterBuilder tokenPar1 = new ParameterBuilder();
tokenPar1.name("x-token").description("后台令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
pars.add(tokenPar.build());
pars.add(tokenPar1.build());
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(info)
.select()
//为当前包路径
.apis(RequestHandlerSelectors.basePackage("com.zrqx"))
.paths(PathSelectors.any())
.build()
.globalOperationParameters(pars);
}
@Override
protected void beforeCreateCode(StringBuffer code) {
code.append("Z");
}
@Override
public String handlerException(HttpServletRequest request, SQLException e) {
return ExceptionUtils.getMessage("请求地址:" + request.getRequestURI() +";", e);
}
}
package com.zrqx.core.enums.member;
import com.zrqx.core.enums.captcha.CaptchaTypeEnum;
import java.util.HashMap;
import java.util.stream.Stream;
/**
* 注册方式
* @author lpf
* @date 2020-06-24
*/
public enum RegisterTypeEnum {
/** */
QQ("qq", "QQ"),
WECHAT("wechat", "微信"),
PHONE("phone","手机"),
SIMPLE("simple", "simple");
private final String code;
private final String name;
private static final HashMap<String,String> MAP = new HashMap<String,String>();
static {
stream().forEach(e -> {
MAP.put(e.code, e.name);
});
}
public static Stream<RegisterTypeEnum> stream(){
return Stream.of(values());
}
private RegisterTypeEnum(String code, String name) {
this.code = code;
this.name = name;
}
public static boolean isExist(String code) {
return stream().anyMatch(e -> e.code.equals(code));
}
public static String getName(String code) {
return stream().filter(e -> e.code.equals(code)).findFirst().map(e -> e.name).orElse(null);
}
public String getCode() {
return code;
}
public String getName() {
return name;
}
public static HashMap<String, String> getMap() {
return MAP;
}
}
package com.zrqx.core.enums.useragent;
import com.zrqx.core.util.useragent.Utils;
public enum Application {
HOTMAIL(Manufacturer.MICROSOFT, 1, "Windows Live Hotmail",
new String[] { "mail.live.com", "hotmail.msn" }, ApplicationType.WEBMAIL),
GMAIL( Manufacturer.GOOGLE, 5, "Gmail",
new String[] { "mail.google.com" }, ApplicationType.WEBMAIL),
YAHOO_MAIL( Manufacturer.YAHOO, 10, "Yahoo Mail",
new String[] { "mail.yahoo.com" }, ApplicationType.WEBMAIL),
COMPUSERVE( Manufacturer.COMPUSERVE, 20, "Compuserve",
new String[] { "csmail.compuserve.com" }, ApplicationType.WEBMAIL),
AOL_WEBMAIL( Manufacturer.AOL, 30, "AOL webmail",
new String[] { "webmail.aol.com" }, ApplicationType.WEBMAIL),
/**
* MobileMe webmail client by Apple. Previously known as .mac.
*/
MOBILEME( Manufacturer.APPLE, 40, "MobileMe",
new String[] { "www.me.com" }, ApplicationType.WEBMAIL),
/**
* Mail.com
* Mail.com provides consumers with web-based e-mail services
*/
MAIL_COM( Manufacturer.MMC, 50, "Mail.com",
new String[] { ".mail.com" }, ApplicationType.WEBMAIL),
/**
* Popular open source webmail client. Often installed by providers or privately.
*/
HORDE( Manufacturer.OTHER, 50, "horde",
new String[] { "horde" }, ApplicationType.WEBMAIL),
OTHER_WEBMAIL(Manufacturer.OTHER, 60, "Other webmail client",
new String[] { "webmail", "webemail" }, ApplicationType.WEBMAIL),
UNKNOWN(Manufacturer.OTHER, 0, "Unknown",
new String[0], ApplicationType.UNKNOWN);
private final short id;
private final String name;
private final String[] aliases;
private final ApplicationType applicationType;
private final Manufacturer manufacturer;
private Application(Manufacturer manufacturer, int versionId, String name,
String[] aliases, ApplicationType applicationType) {
this.id = (short) ((manufacturer.getId() << 8) + (byte) versionId);
this.name = name;
this.aliases = Utils.toLowerCase(aliases);
this.applicationType = applicationType;
this.manufacturer = manufacturer;
}
public short getId() {
return id;
}
public String getName() {
return name;
}
/**
* @return the applicationType
*/
public ApplicationType getApplicationType() {
return applicationType;
}
/**
* @return the manufacturer
*/
public Manufacturer getManufacturer() {
return manufacturer;
}
/*
* Checks if the given referrer string matches to the application. Only
* checks for one specific application.
*/
public boolean isInReferrerString(String referrerString) {
final String referrerStringLowercase = referrerString.toLowerCase();
return isInReferrerStringLowercase(referrerStringLowercase);
}
private boolean isInReferrerStringLowercase(final String referrerStringLowercase) {
return Utils.contains(referrerStringLowercase, aliases);
}
/*
* Iterates over all Application to compare the signature with the referrer
* string. If no match can be found Application.UNKNOWN will be returned.
*/
public static Application parseReferrerString(String referrerString) {
// skip the empty and "-" referrer
if (referrerString != null && referrerString.length() > 1) {
String referrerStringLowercase = referrerString.toLowerCase();
for (Application applicationInList : Application.values()) {
if (applicationInList.isInReferrerStringLowercase(referrerStringLowercase))
return applicationInList;
}
}
return Application.UNKNOWN;
}
/**
* Returns the enum constant of this type with the specified id. Throws
* IllegalArgumentException if the value does not exist.
*
* @param id Id of the application
* @return Application enum
*/
public static Application valueOf(short id) {
for (Application application : Application.values()) {
if (application.getId() == id)
return application;
}
// same behavior as standard valueOf(string) method
throw new IllegalArgumentException("No enum const for id " + id);
}
}
/*
* Copyright (c) 2008-2018, Harald Walker (bitwalker.eu) and contributing developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the
* following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* * Neither the name of bitwalker nor the names of its
* contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.zrqx.core.enums.useragent;
/**
* Enum constants classifying the different types of applications which are common in referrer strings
* @author harald
*
*/
public enum ApplicationType {
/**
* Webmail service like Windows Live Hotmail and Gmail.
*/
WEBMAIL("Webmail client"),
UNKNOWN("unknown");
private String name;
private ApplicationType(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
/*
* Copyright (c) 2008-2018, Harald Walker (bitwalker.eu) and contributing developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the
* following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* * Neither the name of bitwalker nor the names of its
* contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.zrqx.core.enums.useragent;
/**
* Enum constants classifying the different types of browsers which are common in user-agent strings
* @author harald
*
*/
public enum BrowserType {
/**
* Standard web-browser
*/
WEB_BROWSER("Browser"),
/**
* Special web-browser for mobile devices
*/
MOBILE_BROWSER("Browser (mobile)"),
/**
* Text only browser like the good old Lynx
*/
TEXT_BROWSER("Browser (text only)"),
/**
* Email client like Thunderbird
*/
EMAIL_CLIENT("Email Client"),
/**
* Search robot, spider, crawler,...
*/
ROBOT("Robot"),
/**
* Downloading tools
*/
TOOL("Downloading tool"),
/**
* Application
*/
APP("Application"),
UNKNOWN("unknown");
private String name;
private BrowserType(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
/*
* Copyright (c) 2008-2018, Harald Walker (bitwalker.eu) and contributing developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the
* following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* * Neither the name of bitwalker nor the names of its
* contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.zrqx.core.enums.useragent;
/**
* Enum contact for the type of used device
* @author harald
*
*/
public enum DeviceType {
/**
* Standard desktop or laptop computer
*/
COMPUTER("Computer"),
/**
* Mobile phone or similar small mobile device
*/
MOBILE("Mobile"),
/**
* Small tablet type computer.
*/
TABLET("Tablet"),
/**
* Game console like the Wii or Playstation.
*/
GAME_CONSOLE("Game console"),
/**
* Digital media receiver like the Google TV.
*/
DMR("Digital media receiver"),
/**
* Miniature device like a smart watch or interactive glasses
*/
WEARABLE("Wearable computer"),
/**
* Other or unknow type of device.
*/
UNKNOWN("Unknown");
String name;
private DeviceType(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
/*
* Copyright (c) 2008-2018, Harald Walker (bitwalker.eu) and contributing developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the
* following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* * Neither the name of bitwalker nor the names of its
* contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.zrqx.core.enums.useragent;
/**
* Enum constants representing manufacturers of operating systems and client software.
* Manufacturer could be used for specific handling of browser requests.
* @author harald
*/
public enum Manufacturer {
/**
* Unknow or rare manufacturer
*/
OTHER(1, "Other"),
/**
* Microsoft Corporation
*/
MICROSOFT(2, "Microsoft Corporation"),
/**
* Apple Inc.
*/
APPLE(3, "Apple Inc."),
/**
* Sun Microsystems, Inc.
*/
SUN(4, "Sun Microsystems, Inc."),
/**
* Symbian Ltd.
*/
SYMBIAN(5, "Symbian Ltd."),
/**
* Nokia Corporation
*/
NOKIA(6, "Nokia Corporation"),
/**
* Research In Motion Limited
*/
BLACKBERRY(7, "Research In Motion Limited"),
/**
* Hewlett-Packard Company, previously Palm
*/
HP(8, "Hewlett Packard"),
/**
* Sony Ericsson Mobile Communications AB
*/
SONY_ERICSSON(9, "Sony Ericsson Mobile Communications AB"),
/**
* Samsung Electronics
*/
SAMSUNG(20, "Samsung Electronics"),
/**
* Sony Computer Entertainment, Inc.
*/
SONY(10, "Sony Computer Entertainment, Inc."),
/**
* Nintendo
*/
NINTENDO(11, "Nintendo"),
/**
* Opera Software ASA
*/
OPERA(12, "Opera Software ASA"),
/**
* Mozilla Foundation
*/
MOZILLA(13, "Mozilla Foundation"),
/**
* Google Inc.
*/
GOOGLE(15, "Google Inc."),
/**
* CompuServe Interactive Services, Inc.
*/
COMPUSERVE(16, "CompuServe Interactive Services, Inc."),
/**
* Yahoo Inc.
*/
YAHOO(17, "Yahoo Inc."),
/**
* AOL LLC.
*/
AOL(18, "AOL LLC."),
/**
* Mail.com Media Corporation
*/
MMC(19, "Mail.com Media Corporation"),
/**
* Amazon.com, Inc.
*/
AMAZON(24, "Amazon.com, Inc."),
/**
* Roku sells home digital media products
*/
ROKU(21, "Roku, Inc."),
/**
* Adobe Systems Inc.
*/
ADOBE(23, "Adobe Systems Inc."),
/**
* Canonical Ltd.
*/
CONONICAL(25,"Canonical Ltd."),
/**
* Linux Foundation, owner of the Tizen Project
*/
LINUX_FOUNDATION(26,"Linux Foundation"),
/**
* UC
*/
UCBROWSER(27, "UC Mobile Limited"),
/**
* QQ
*/
QQBROWSER(28, "Tencent"),
//360
BROWSER_360(29, "Qihoo 360 Technology Co. Ltd."),
//baidu
BAIDU(30, "Baidu");
private final short id;
private final String name;
private Manufacturer(int id, String name) {
this.id = (byte) id;
this.name = name;
}
/**
* @return the id
*/
public short getId() {
return id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
}
/*
* Copyright (c) 2008-2018, Harald Walker (bitwalker.eu) and contributing developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the
* following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* * Neither the name of bitwalker nor the names of its
* contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.zrqx.core.enums.useragent;
/**
* Enum constants classifying the different types of rendering engines which are being used by browsers.
* @author harald
*
*/
public enum RenderingEngine {
/**
* EdgeHTML is a proprietary layout engine developed for the Microsoft Edge web browser, developed by Microsoft.
*/
EDGE_HTML("EdgeHTML"),
/**
* Trident is the the Microsoft layout engine, mainly used by Internet Explorer.
*/
TRIDENT("Trident"),
/**
* HTML parsing and rendering engine of Microsoft Office Word, used by some other products of the Office suite instead of Trident.
*/
WORD("Microsoft Office Word"),
/**
* Open source and cross platform layout engine, used by Firefox and many other browsers.
*/
GECKO("Gecko"),
/**
* Layout engine based on KHTML, used by Safari, Chrome and some other browsers.
*/
WEBKIT("WebKit"),
/**
* Proprietary layout engine by Opera Software ASA
*/
PRESTO("Presto"),
/**
* Original layout engine of the Mozilla browser and related products. Predecessor of Gecko.
*/
MOZILLA("Mozilla"),
/**
* Layout engine of the KDE project
*/
KHTML("KHTML"),
/**
* Other or unknown layout engine.
*/
BLINK("Blink"),
/**
* Layout engine developed as part ofthe Chromium project. Fored from WebKit.
*/
OTHER("Other");
String name;
private RenderingEngine(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
package com.zrqx.core.form;
import com.zrqx.core.components.captcha.form.CaptchaForm;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @author lpf
* @date 2020-06-28
*/
@Data
public abstract class AbstractLoginForm {
@ApiModelProperty("验证码form")
private CaptchaForm captchaForm;
}
package com.zrqx.core.form;
import javax.servlet.http.HttpServletRequest;
import com.zrqx.core.model.member.UserAgentInfo;
import com.zrqx.core.util.spring.SpringContextUtils;
import com.zrqx.core.util.useragent.UserAgentParseUtil;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 登录上下文
* @author lpf
* @date 2020-06-28
*/
@Data
public class BaseLoginForm<T> {
@ApiModelProperty("前台提交的参数内容")
private T reqForm;
@ApiModelProperty("请求信息")
private HttpServletRequest request;
@ApiModelProperty("用户来源")
private String sourceType;
@ApiModelProperty("用户使用设备信息")
private UserAgentInfo agentInfo;
public BaseLoginForm(T reqForm) {
this.reqForm = reqForm;
this.request = SpringContextUtils.getRequest();
this.agentInfo = UserAgentParseUtil.getUserAgentInfo(this.request);
}
}
package com.zrqx.core.form;
import io.swagger.annotations.ApiModel;
import lombok.Data;
/**
* 手机号快捷登录
* @author lpf
* @date 2020-06-28
*/
@Data
@ApiModel(value = "PhoneLoginForm", description = "手机号快捷登录form")
public class PhoneAbstractLoginForm extends AbstractLoginForm {
}
package com.zrqx.core.form;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @author lpf
* @date 2020-06-30
*/
@Data
@ApiModel(value = "PhonePassordForm", description = "手机号首次登录设置密码")
public class PhonePassordForm {
@ApiModelProperty("密码")
private String password;
}
package com.zrqx.core.form;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @author lpf
* @date 2020-06-30
*/
@Data
@ApiModel(value = "RegisterForm", description = "注册form")
public class RegisterFormAbstract extends SimpleAbstractLoginForm {
@ApiModelProperty("机构码")
private String code;
}
package com.zrqx.core.form;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @author lpf
* @date 2020-07-02
*/
@Data
@ApiModel(value = "ResetPasswordForm", description = "重置密码form")
public class ResetPasswordForm {
@ApiModelProperty("用户token")
private String token;
@ApiModelProperty("设置密码")
private String password;
@ApiModelProperty("确认密码")
private String again;
}
package com.zrqx.core.form;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 账号密码登录
* @author lpf
* @date 2020-06-28
*/
@Data
@ApiModel(value = "SimpleLoginForm", description = "账号密码登录form")
public class SimpleAbstractLoginForm extends AbstractLoginForm {
@ApiModelProperty("账号|手机号")
private String account;
@ApiModelProperty("密码")
private String password;
}
package com.zrqx.core.form;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @author lpf
* @date 2020-06-29
*/
@Data
@ApiModel(value = "ThirdLoginForm", description = "第三方登录form")
public class ThirdLoginForm{
@ApiModelProperty("第三方标识")
private String code;
}
package com.zrqx.core.form;
import io.swagger.annotations.ApiModel;
import lombok.Data;
/**
* @author lpf
* @date 2020-06-30
*/
@Data
@ApiModel(value = "ThridPhoneForm", description = "手机号首次登录设置密码")
public class ThridPhoneFormAbstract extends AbstractLoginForm {
}
......@@ -14,5 +14,5 @@ public class LoginForm {
@ApiModelProperty(value="验证码 账号或密码错误 5次以上 需填写")
private String code;
@ApiModelProperty("登录渠道 0 PC,1 WAP,2 Android,3 iOS")
private Integer channel = 0;
private String channel = "0";
}
......@@ -6,7 +6,7 @@ import lombok.Data;
public class SmsForm {
@ApiModelProperty(value="待发送手机号,必填")
private String phone;
@ApiModelProperty(value="用户注册验证码为0,修改密码验证码为1,必填")
@ApiModelProperty(value="用户注册验证码为0,修改密码验证码为1,必填 ,前台短信验证码3 修改手机号传 2 ")
private Integer type;
@ApiModelProperty(value="用户名")
private String name;
......
package com.zrqx.core.model.member;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Date;
import javax.persistence.GeneratedValue;
......@@ -10,11 +7,16 @@ import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.zrqx.core.util.encry.annotation.Encrypt;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
@Table(name = "m_LoginLog")
@ApiModel(value = "LoginLog", description = "会员登录日志")
@Encrypt
public class LoginLog {
@Id
@GeneratedValue(generator = "JDBC")
......@@ -27,14 +29,37 @@ public class LoginLog {
@ApiModelProperty("登录时间")
private Date createTime;
@ApiModelProperty("登录渠道 0 PC,1 WAP,2 Android,3 iOS")
private Integer channel;
private String channel;
@ApiModelProperty("登录成功1 失败 0")
private Integer type;
@ApiModelProperty("描述")
private String description;
@Transient
@ApiModelProperty("登录渠道 0 PC,1 WAP,2 Android,3 iOS")
private String channel_zh;
///
@ApiModelProperty("会员id")
private Integer memberId;
@Encrypt
@ApiModelProperty("操作人手机号,已加密")
private String phone;
@ApiModelProperty("操作人用户名")
private String name;
@ApiModelProperty("备注信息")
private String remark;
@ApiModelProperty("浏览器名称")
private String browserName;
@ApiModelProperty("浏览器类型")
private String browserType;
@ApiModelProperty("浏览器版本")
private String browserVersion;
/**
* {@link com.zrqx.core.enums.useragent.Manufacturer}
*/
@ApiModelProperty("浏览器厂商")
private String manufacturer;
@ApiModelProperty("操作系统名称")
private String operatingSystemName;
@ApiModelProperty("访问设备类型 Computer Mobile Tablet UNKNOWN")
private String deviceType;
}
......@@ -54,4 +54,11 @@ public class Member {
@ApiModelProperty("token")
@Transient
private String token;
//组件库
@ApiModelProperty("注册方式")
private String registerType;
@ApiModelProperty("用户来源")
private String sourceType;
@ApiModelProperty("机构码")
private String code;
}
package com.zrqx.core.model.member;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
public class UserAgentInfo {
@ApiModelProperty("浏览器名称")
private String browserName;
@ApiModelProperty("浏览器类型")
private String browserType;
@ApiModelProperty("浏览器版本")
private String browserVersion;
/**
* {@link com.zrqx.core.enums.useragent.Manufacturer}
*/
@ApiModelProperty("浏览器厂商")
private String manufacturer;
@ApiModelProperty("操作系统名称")
private String operatingSystemName;
@ApiModelProperty("访问设备类型 Computer Mobile Tablet")
private String deviceType;
}
......@@ -292,6 +292,20 @@ public abstract class BaseServiceImpl<M, ID extends Serializable> implements Bas
}
return this.notNull(m);
}
@Override
public Optional<M> ofNullable(Example example) {
List<M> list = this.selectByExample(example);
if (ArrayUtils.empty(list)) {
return Optional.empty();
}
return Optional.of(list.get(0));
}
@Override
public Optional<M> ofNullableCriteria(Consumer<Criteria> consumer) {
Example example = this.createExample();
Criteria criteria = example.createCriteria();
consumer.accept(criteria);
return this.ofNullable(example);
}
}
\ No newline at end of file
package com.zrqx.core.service;
import java.io.Serializable;
import java.util.Optional;
import java.util.function.Consumer;
import tk.mybatis.mapper.entity.Example;
public interface NotNullInterface<M, ID extends Serializable> {
/**
......@@ -39,6 +42,17 @@ public interface NotNullInterface<M, ID extends Serializable> {
* @date: 2019年2月20日 下午4:58:55
*/
M notNull(Consumer<M> consumer);
/**
* 根据Criteria查询可能存在的对象
* @param consumer
* @return
*/
Optional<M> ofNullableCriteria(Consumer<Example.Criteria> consumer);
/**
* 根据example查询可能存在的对象
* @param example
* @return
*/
Optional<M> ofNullable(Example example);
}
/**
* @author ray
* @date 2018年8月24日 下午3:22:57
*/
package com.zrqx.core.util;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/** java模拟 post get请求发送
* @author ray
* @date 2018年8月24日下午3:22:57
*/
public class HttpsUtils {
/**
* java模拟get请求
* @return
* @throws Exception
* @author ray
* @date: 2018年8月24日 下午3:25:34
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//设置连接主机超时
connection.setConnectTimeout(30000);
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* java模拟post请求
* @return
* @throws Exception
* @author ray
* @date: 2018年8月24日 下午3:25:34
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
public static String sendPost(String url, Map<String,? extends Object> paramsMap) {
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
//配置连接超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.setSocketTimeout(5000)
.setRedirectsEnabled(true)
.build();
HttpPost httpPost = new HttpPost(url);
//设置超时时间
httpPost.setConfig(requestConfig);
//装配post请求参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
for (String key : paramsMap.keySet()) {
list.add(new BasicNameValuePair(key, String.valueOf(paramsMap.get(key))));
}
try {
//将参数进行编码为合适的格式,如将键值对编码为param1=value1&param2=value2
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "utf-8");
httpPost.setEntity(urlEncodedFormEntity);
//执行 post请求
CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpPost);
String strRequest = "";
if (null != closeableHttpResponse && !"".equals(closeableHttpResponse)) {
System.out.println(closeableHttpResponse.getStatusLine().getStatusCode());
if (closeableHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity httpEntity = closeableHttpResponse.getEntity();
strRequest = EntityUtils.toString(httpEntity,"utf-8");
} else {
strRequest = "Error Response" + closeableHttpResponse.getStatusLine().getStatusCode();
}
}
return strRequest;
} catch (ClientProtocolException e) {
e.printStackTrace();
return "协议异常";
} catch (ParseException e) {
e.printStackTrace();
return "解析异常";
} catch (IOException e) {
e.printStackTrace();
return "传输异常";
} finally {
try {
if (closeableHttpClient != null) {
closeableHttpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.zrqx.core.util;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
*
* @author lpf
* @date 2020-07-01 9:49
*/
public class IpUtil {
private static final String UNKNOWN = "unKnown";
private static final String LOCAL_IP4 = "127.0.0.1";
private static final String LOCAL_IP6 = "0:0:0:0:0:0:0:1";
public static String getIp(HttpServletRequest request){
String ip = request.getHeader("x-forwarded-for");
if(ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
/**
* X-Forwarded-For
* 这是一个 Squid 开发的字段,只有在通过了 HTTP 代理或者负载均衡服务器时才会添加该项。
* 格式为X-Forwarded-For: client1, proxy1, proxy2,一般情况下,第一个ip为客户端真实ip,
* 后面的为经过的代理服务器ip。现在大部分的代理都会加上这个请求头
*
* Proxy-Client-IP/WL- Proxy-Client-IP
* 这个一般是经过apache http服务器的请求才会有,用apache http做代理时一般会加上Proxy-Client-IP请求头,
* 而WL- Proxy-Client-IP是他的weblogic插件加上的头
*
* HTTP_CLIENT_IP
* 有些代理服务器会加上此请求头
*
* X-Real-IP
* nginx代理一般会加上此请求头。
*
*/
public static String getIpAddress(HttpServletRequest request) {
//获取nginx代理的ip
String xip = request.getHeader("X-Real-IP");
//一个 Squid 开发的字段,只有在通过了 HTTP 代理或者负载均衡服务器时才会添加该项
String xfor = request.getHeader("X-Forwarded-For");
if (StringUtils.isNotEmpty(xfor) && !UNKNOWN.equalsIgnoreCase(xfor)) {
int index = xfor.indexOf(",");
return index != -1 ? xfor.substring(0, index) : xfor;
} else {
xfor = xip;
if (StringUtils.isNotEmpty(xip) && !UNKNOWN.equalsIgnoreCase(xip)) {
return xip;
} else {
//经过apache http服务器的请求才会有
if (StringUtils.isBlank(xip) || UNKNOWN.equalsIgnoreCase(xip)) {
xfor = request.getHeader("Proxy-Client-IP");
}
//经过apache http服务器的请求才会有
if (StringUtils.isBlank(xfor) || UNKNOWN.equalsIgnoreCase(xfor)) {
xfor = request.getHeader("WL-Proxy-Client-IP");
}
//有些代理服务器会加上此请求头
if (StringUtils.isBlank(xfor) || UNKNOWN.equalsIgnoreCase(xfor)) {
xfor = request.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isBlank(xfor) || UNKNOWN.equalsIgnoreCase(xfor)) {
xfor = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isBlank(xfor) || UNKNOWN.equalsIgnoreCase(xfor)) {
xfor = request.getRemoteAddr();
}
return xfor;
}
}
}
public static String getIpAddr(HttpServletRequest request){
String ipAddress = request.getHeader("x-forwarded-for");
if(ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if(ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if(ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if(LOCAL_IP4.equals(ipAddress) || LOCAL_IP6.equals(ipAddress)){
//根据网卡取本机配置的IP
InetAddress inet=null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ipAddress= inet.getHostAddress();
}
}
//对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
//"***.***.***.***".length() = 15
int end = 15;
if(ipAddress!=null && ipAddress.length()>end){
String str = ",";
if(ipAddress.indexOf(str)>0){
ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
}
}
return ipAddress;
}
}
......@@ -6,6 +6,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
......@@ -48,7 +49,15 @@ public class StringUtil{
return flag;
}
public static String getRandomNumber(int num) {
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < num; i ++) {
sb.append(random.nextInt(10));
}
return sb.toString();
}
/**
* 给定指定字符串res,去除字符串首尾的指定字符c
*
......
......@@ -2,6 +2,7 @@ package com.zrqx.core.util.encry.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
......@@ -13,8 +14,9 @@ import java.lang.annotation.Target;
* @date 2018年11月16日下午5:05:43
*/
@Documented
@Inherited
@Target({ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Encrypt {
}
package com.zrqx.core.util.exception;
import java.util.Date;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* 异常工具类
* @author lpf
* @date 2019年8月22日下午4:19:03
*/
public class ExceptionUtils {
/**
* 获取异常的异常栈全部信息
* @param e
* @return
* @author lpf
* @date: 2019年8月22日 下午4:30:18
*/
public static String getMessage(Exception e){
StringBuffer result = Stream.of(e.getStackTrace())
.map(StackTraceElement :: toString)
.map(s -> {
StringBuffer sb = new StringBuffer(s);
sb.append("<br>");
return sb;
}).collect(Collectors.reducing(StringBuffer :: append))
.orElseGet(() -> new StringBuffer("ExceptionUtils#getMessage组装异常信息失败;"));
return "异常时间:" + new Date().toString() + "<br>" + result.toString();
}
public static String getMessage(String before, Exception e) {
return before + ExceptionUtils.getMessage(e);
}
}
package com.zrqx.core.util.useragent;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.util.regex.Pattern.CASE_INSENSITIVE;
/**
* Extracts version from provided UserAgentInfo string using pattern.
* @author alexr
*/
public class PatternBasedVersionFetcher implements VersionFetcher {
private final Pattern pattern;
public PatternBasedVersionFetcher(String regex) {
this(Pattern.compile(regex, CASE_INSENSITIVE));
}
PatternBasedVersionFetcher(Pattern pattern) {
this.pattern = pattern;
}
@Override
public final Version version(String userAgentString) {
Matcher matcher = pattern.matcher(userAgentString);
if (!matcher.find()) {
return null;
}
return createVersion(matcher);
}
protected Version createVersion(Matcher matcher) {
String fullVersionString = matcher.group(1);
String majorVersion = matcher.group(2);
String minorVersion = "0";
if (matcher.groupCount() > 2) // usually but not always there is a minor version
minorVersion = matcher.group(3);
return new Version (fullVersionString,majorVersion,minorVersion);
}
}
package com.zrqx.core.util.useragent;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* There are 2 types of user agent strings that present Safari: one that contains fragment {@code Version/1.2.3} from where the version of
* Safari browser can be extracted and others that do not.
* Fortunately Safari User-Agent string contains version of WebKit that can be used to discover the version of Safari browser.
* This class contains mapping between version of WebKit and Safari browser taken from @see <a href="https://en.wikipedia.org/wiki/Safari_version_history">Wikipedia</a>.
* In most cases version of WebKit exists and uniquely identifies version of Safari browser.
* Unfortunately there are several exceptions.
* <ol>
* <li>There is no information about WebKit version for some Safari versions. This requires additional discovery</li>
* <li>
* The same version of WebKit used in several versions of Safari that causes ambiguity. Fortunately in all found cases these different versions of Safari
* are built for different operating systems, so theoretically we can distinguish between different versions of Safari with the same web kit by using
* information about operating system. Such feature however is not supported by the environment right now.
* </li>
* </ol>
* @author alexr
*/
// https://en.wikipedia.org/wiki/Safari_version_history
public class SafariUtils {
private static final String[][] webKitToSafariVersion = new String[][] {
{"48", "0.8"},
{"73", "0.9"},
{"85", "1.0"},
{"85.8.5", "1.0.3"},
{"100", "1.1"},
{"125", "1.2"},
{"312", "1.3"},
{"312.3", "1.3.1"},
{"312.5", "1.3.2"},
{"312.6", "1.3.2"},
{"412", "2.0"},
{"416.11", "2.0.2"},
{"419.3", "2.0.4"},
{"522.11", "3.0"},
{"522.12", "3.0.2"},
{"522.12.1", "3.0.3"},
{"523.10", "3.0.4"},
{"525.20", "3.1.1"},
{"525.21", "3.1.2"},
{"525.26", "3.2"},
{"525.27", "3.2.1"},
{"525.28", "3.2.3"},
// {"530.17", "4.0.1"}, // ambiguity: Safari 4.0 for Mac 10.4-10.5 and Safari 4.0.1 for Windows vista and XP
{"530.18", "4.0.1"},
{"530.19", "4.0.2"},
{"531.9", "4.0.3"},
{"531.21.10", "4.0.4"},
{"531.22.7", "4.0.5"},
// {"533.16", "4.1"}, // ambiguity: Safari 4.1 on MacOsX 10.4, Safari 5.0 on MacOsX 10.5-10.6 and Windows XP, Vista and 7
// {"533.17.8", "4.1.1"}, // ambiguity: Safari 4.1.1 on MacOsX 10.4, Safari 5.0.1 on MacOsX 10.5-10.6 and Windows XP, Vista and 7
//{"533.18.5", "4.1.2"}, // ambiguity: Safari 4.1.2 on MacOsX 10.4, Safari 5.0.2 on MacOsX 10.5-10.6 and Windows XP, Vista and 7
//{"533.19.4", "4.1.3"},// ambiguity: Safari 4.1.3 on MacOsX 10.4, Safari 5.0.3 on MacOsX 10.5-10.6 and Windows XP, Vista and 7
{"533.20.27", "5.0.4"},
{"533.21.1", "5.0.5"},
{"533.22.3", "5.0.6"},
{"534.48.3", "5.1"},
{"534.51.22", "5.1.1"},
{"534.52.7", "5.1.2"},
{"534.53.10", "5.1.3"},
{"534.54.16", "5.1.4"},
{"534.55.3", "5.1.5"},
{"534.56.5", "5.1.6"},
{"534.57.2", "5.1.7"},
{"534.58.2", "5.1.8"},
{"534.59.8", "5.1.9"},
{"534.59.10", "5.1.10"},
{"536.25", "6.0"},
{"536.26", "6.0.1"},
{"536.26.17", "6.0.2"},
{"536.28.10", "6.0.3"},
{"536.29.13", "6.0.4"},
{"536.30.1", "6.0.5"},
{"537.43.58", "6.1"},
//{"537.73.11", "6.1.1"}, // ambiguity: Safari 6.1.1 on OsX 10.7-10.8 and 7.0.1 on OsX 10.9
// data is absent in wikipedia
// {"", "6.1.2"},
// {"", "6.1.3"},
// {"", "6.1.4"},
// {"", "6.1.5"},
// {"537.78.2", "6.1.6"}, // ambiguity: Safari 6.1.6 on OsX 10.7-10.8 and 7.0.6 on OsX 10.9
// data is absent in wikipedia
// {"", "6.2"},
// {"", "6.2.1"},
// {"", "6.2.2"},
// {"", "6.2.3"},
// {"", "6.2.4"},
// {"", "6.2.5"},
// {"", "6.2.6"},
// {"", "6.2.7"},
// {"537.85.17", "6.2.8"}, // ambiguity: Safari 6.2.8 on OsX 10.8 and 7.1.8 on OsX 10.9
{"537.71", "7.0"},
// data is absent in wikipedia
// {"", "7.0.2"},
{"537.75.14", "7.0.3"},
{"537.76.4", "7.0.4"},
{"537.77.4", "7.0.5"},
////{"537.78.2", "7.0.6"}, //TODO ambiguity
// data is absent in wikipedia
// {"", "7.1"},
// {"", "7.1.1"},
// {"", "7.1.2"},
// {"", "7.1.3"},
// {"", "7.1.4"},
// {"", "7.1.5"},
// {"", "7.1.6"},
// {"", "7.1.7"},
{"538.35.8", "8.0"},
// data is absent in wikipedia
// {"", "8.0.1"},
// {"", "8.0.2"},
// {"", "8.0.3"},
// {"", "8.0.4"},
// {"", "8.0.5"},
{"600.6.3", "8.0.6"},
{"600.7.12", "8.0.7"},
// data is absent in wikipedia
// {"", "8.0.8"},
// {"", "9.0"},
{"601.2.7", "9.0.1"},
{"601.3.9", "9.0.2"},
{"601.4.4", "9.0.3"},
{"601.5.17", "9.1"},
{"601.6.17", "9.1.1"},
{"601.7.1", "9.1.2"},
{"601.7.8", "9.1.3"},
// Safari 10.x
{"602.1.50", "10"},
{"602.2.14", "10.0.1"},
{"602.3.12", "10.0.2"},
{"602.4.8", "10.0.3"},
{"603.1.30", "10.1"}, // New web technology additions and improvements.
{"603.2.4", "10.1.1"},
{"603.3.8", "10.1.2"},
//Safari 11.x ... TODO
{"522.11.3", "3.0"},
{"522.13.1", "3.0.2"},
{"522.12.2", "3.0.1"},
{"522.15.5", "3.0.3"},
{"523.12.9", "3.0.4"},
{"523.13", "3.0.4"},
{"523.15", "3.0.4"},
// mac os 10.4 - 10.5 and Windows XP, Vista
{"525.13", "3.1"},
{"525.17", "3.1.1"},
{"525.21", "3.1.2"},
{"525.26.13", "3.2"},
{"525.27.1", "3.2.1"},
{"525.28.1", "3.2.2"},
{"525.29.1", "3.2.3"},
{"526.12.2", "4.0"},
{"528.1.1", "4.0"},
{"526.11.2", "4.0"}, // actually 4.0 beta
// 4.0 and 4.0 beta but since it is the same version we do not distinguish between 4.0 and 4.0 beta
{"528.16", "4.0"},
{"528.17", "4.0"},
// end of 4.0 and 4.0 beta
{"530.19.1", "4.0.2"},
{"531.9.1", "4.0.3"},
{"531.22.7", "4.0.5"},
{"534.50", "5.1"},
};
private static final Map<String, Version> safariVersions;
static {
Map<String, Version> versions = new HashMap<String, Version>();
for (String[] pair : webKitToSafariVersion) {
String webKitVersion = pair[0];
String browserVersion = pair[1];
String[] parts = browserVersion.split("\\.");
String majorVersion = parts[0];
String minorVersion = parts.length > 1 ? parts[1] : null;
Version version = new Version(browserVersion, majorVersion, minorVersion);
versions.put(webKitVersion, version);
}
safariVersions = Collections.unmodifiableMap(versions);
}
public static Map<String, Version> getWebKitToSafariVersion() {
return safariVersions;
}
}
package com.zrqx.core.util.useragent;
/**
* Implementation of {@link VersionFetcher} that holds a list of other {@link VersionFetcher}
* and calls them sequentially until any of them manages to find version.
* @author alexr
*/
public class SequentialVersionFetcher implements VersionFetcher {
private final VersionFetcher[] fetchers;
public SequentialVersionFetcher(VersionFetcher first, VersionFetcher... others) {
fetchers = new VersionFetcher[others.length + 1];
fetchers[0] = first;
for (int i = 0; i < others.length; i++) {
fetchers[i+1] = others[i];
}
}
@Override
public Version version(String str) {
for (VersionFetcher fetcher : fetchers) {
Version version = fetcher.version(str);
if (version != null) {
return version;
}
}
return null;
}
}
/*
* Copyright (c) 2008-2018, Harald Walker (bitwalker.eu) and contributing developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the
* following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* * Neither the name of bitwalker nor the names of its
* contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.zrqx.core.util.useragent;
import java.io.Serializable;
import com.zrqx.core.enums.useragent.Browser;
import com.zrqx.core.enums.useragent.OperatingSystem;
/**
* Container class for user-agent information with operating system and browser details.
* Can decode user-agent strings.
* <br><br>
* Resources:<br>
* <a href="http://www.useragentstring.com">User Agent String.Com</a><br>
* <a href="http://www.myuseragentstring.com/">My User Agent String</a><br>
* <a href="http://www.user-agents.org">List of User-Agents</a><br>
* <a href="http://user-agent-string.info">user-agent-string.info</a><br>
* <a href="http://www.zytrax.com/tech/web/browser_ids.htm">Browser ID (User-Agent) Strings</a><br>
* <a href="http://www.zytrax.com/tech/web/mobile_ids.html">Mobile Browser ID (User-Agent) Strings</a><br>
* <a href="http://www.joergkrusesweb.de/internet/browser/user-agent.html">Browser-Kennungen</a><br>
* <a href="http://deviceatlas.com/devices">Device Atlas - Mobile Device Intelligence</a><br>
* <a href="http://mobileopera.com/reference/ua">Mobile Opera user-agent strings</a><br>
* <a href="http://en.wikipedia.org/wiki/S60_platform">S60 platform</a><br>
* <a href="http://msdn.microsoft.com/en-us/library/ms537503.aspx">Understanding User-Agent Strings</a><br>
* <a href="http://developer.sonyericsson.com/site/global/docstools/browsing/p_browsing.jsp">Sony Ericsson Web Docs & Tools</a><br>
* <a href="http://developer.apple.com/internet/safari/faq.html#anchor2">What is the Safari user-agent string</a><br>
* <a href="http://www.pgts.com.au/pgtsj/pgtsj0208c.html">List of User Agent Strings</a><br>
* <a href="http://blogs.msdn.com/iemobile/archive/2006/08/03/Detecting_IE_Mobile.aspx">Detecting Internet Explorer Mobile's User-Agent on the server</a>
*/
/**
* @author harald
*
*/
public class UserAgent implements Serializable
{
private static final long serialVersionUID = 7025462762784240212L;
private OperatingSystem operatingSystem;
private Browser browser;
private int id;
private String userAgentString;
/**
* This constructor is created for APIs that require default constructor
* and should never be used directly.
* @deprecated Use {@link #UserAgent(OperatingSystem, Browser)}
*/
@Deprecated
public UserAgent()
{
this(OperatingSystem.UNKNOWN, Browser.UNKNOWN);
}
public UserAgent(OperatingSystem operatingSystem, Browser browser)
{
this.operatingSystem = operatingSystem;
this.browser = browser;
this.id = (( operatingSystem.getId() << 16) + browser.getId());
}
public UserAgent(String userAgentString)
{
String userAgentLowercaseString = userAgentString == null ? null : userAgentString.toLowerCase();
Browser browser = Browser.parseUserAgentLowercaseString(userAgentLowercaseString);
OperatingSystem operatingSystem = OperatingSystem.UNKNOWN;
// BOTs don't have an interesting OS for us
if (browser != Browser.BOT)
operatingSystem = OperatingSystem.parseUserAgentLowercaseString(userAgentLowercaseString);
this.operatingSystem = operatingSystem;
this.browser = browser;
this.id = ((operatingSystem.getId() << 16) + browser.getId());
this.userAgentString = userAgentString;
}
/**
* @param userAgentString User-agent string as provided in the request.
* @return UserAgentInfo
*/
public static UserAgent parseUserAgentString(String userAgentString) {
return new UserAgent(userAgentString);
}
/**
* Detects the detailed version information of the browser. Depends on the userAgent to be available.
* Use it only after using UserAgentInfo(String) or UserAgentInfo.parseUserAgent(String).
* Returns null if it can not detect the version information.
* @return Version
*/
public Version getBrowserVersion() {
return this.browser.getVersion(this.userAgentString);
}
/**
* @return the system
*/
public OperatingSystem getOperatingSystem() {
return operatingSystem;
}
/**
* @return the browser
*/
public Browser getBrowser() {
return browser;
}
/**
* Returns an unique integer value of the operating system and browser combination
* @return the id
*/
public int getId() {
return id;
}
/**
* Combined string representation of both enums
*/
public String toString() {
return this.operatingSystem.toString() + "-" + this.browser.toString();
}
/**
* Returns UserAgentInfo based on specified unique id
* @param id Id value of the user agent.
* @return UserAgentInfo
*/
public static UserAgent valueOf(int id)
{
OperatingSystem operatingSystem = OperatingSystem.valueOf((short) (id >> 16));
Browser browser = Browser.valueOf( (short) (id & 0x0FFFF));
return new UserAgent(operatingSystem,browser);
}
/**
* Returns UserAgentInfo based on combined string representation
* @param name Name of the user agent.
* @return UserAgentInfo
*/
public static UserAgent valueOf(String name)
{
if (name == null)
throw new NullPointerException("Name is null");
String[] elements = name.split("-");
if (elements.length == 2)
{
OperatingSystem operatingSystem = OperatingSystem.valueOf(elements[0]);
Browser browser = Browser.valueOf(elements[1]);
return new UserAgent(operatingSystem,browser);
}
throw new IllegalArgumentException(
"Invalid string for userAgent " + name);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((browser == null) ? 0 : browser.hashCode());
result = prime * result + id;
result = prime * result
+ ((operatingSystem == null) ? 0 : operatingSystem.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final UserAgent other = (UserAgent) obj;
if (browser == null) {
if (other.browser != null)
return false;
} else if (!browser.equals(other.browser))
return false;
if (id != other.id)
return false;
if (operatingSystem == null) {
if (other.operatingSystem != null)
return false;
} else if (!operatingSystem.equals(other.operatingSystem))
return false;
return true;
}
/**
* @return userAgentString
*/
public String getUserAgentString() { return userAgentString; }
}
package com.zrqx.core.util.useragent;
import javax.servlet.http.HttpServletRequest;
import com.zrqx.core.enums.useragent.Browser;
import com.zrqx.core.enums.useragent.DeviceType;
import com.zrqx.core.enums.useragent.OperatingSystem;
import com.zrqx.core.model.member.UserAgentInfo;
public class UserAgentParseUtil {
public static UserAgentInfo getUserAgentInfo(HttpServletRequest request) {
String agent = request.getHeader("User-Agent");
UserAgent userAgent = UserAgent.parseUserAgentString(agent);
//浏览器信息
Browser browser = userAgent.getBrowser();
//操作系统信息
OperatingSystem operatingSystem = userAgent.getOperatingSystem();
DeviceType deviceType = operatingSystem.getDeviceType();
UserAgentInfo result = new UserAgentInfo();
try {
result.setBrowserName(browser.getName());
result.setBrowserType(browser.getBrowserType().getName());
result.setBrowserVersion(userAgent.getBrowserVersion().version);
result.setManufacturer(operatingSystem.getManufacturer().getName());
result.setOperatingSystemName(operatingSystem.getName());
result.setDeviceType(getDeviceType(operatingSystem.getDeviceType()));
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private static String getDeviceType(DeviceType deviceType) {
switch (deviceType) {
case COMPUTER:
return "PC";
case TABLET:
return "PAID";
case MOBILE:
return "PHONE";
default:
return "UNKNOWN";
}
}
}
package com.zrqx.core.util.useragent;
public class Utils {
public static String[] toLowerCase(String[] strArr) {
if (strArr == null) return null;
String[] res = new String[strArr.length];
for (int i=0; i<strArr.length; i++) {
res[i] = strArr[i].toLowerCase();
}
return res;
}
public static boolean contains(String str, String[] strArr) {
if (strArr == null)
return false;
for (String arrStr : strArr) {
if (str.contains(arrStr)) {
return true;
}
}
return false;
}
}
/*
* Copyright (c) 2008-2018, Harald Walker (bitwalker.eu) and contributing developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the
* following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* * Neither the name of bitwalker nor the names of its
* contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.zrqx.core.util.useragent;
/**
* Container for general version information.
* All version information is stored as String as sometimes version information includes alphabetical characters.
* @author harald
*/
public class Version implements Comparable<Version> {
String version;
String majorVersion;
String minorVersion;
/**
* This constructor is created for APIs that require default constructor
* and should never be used directly.
* @deprecated Use {@link #Version(String, String, String)}
*/
@Deprecated
public Version() {
// default constructor for APIs that require it (e.g. JSON serialization)
}
public Version(String version, String majorVersion, String minorVersion) {
super();
this.version = version;
this.majorVersion = majorVersion;
this.minorVersion = minorVersion;
}
public String getVersion() {
return version;
}
public String getMajorVersion() {
return majorVersion;
}
public String getMinorVersion() {
return minorVersion;
}
@Override
public String toString() {
return version;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((majorVersion == null) ? 0 : majorVersion.hashCode());
result = prime * result
+ ((minorVersion == null) ? 0 : minorVersion.hashCode());
result = prime * result + ((version == null) ? 0 : version.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Version other = (Version) obj;
if (majorVersion == null) {
if (other.majorVersion != null)
return false;
} else if (!majorVersion.equals(other.majorVersion))
return false;
if (minorVersion == null) {
if (other.minorVersion != null)
return false;
} else if (!minorVersion.equals(other.minorVersion))
return false;
if (version == null) {
if (other.version != null)
return false;
} else if (!version.equals(other.version))
return false;
return true;
}
public int compareTo(Version other) {
if (other == null) {
return 1;
}
String[] versionParts = version.split("\\.");
String[] otherVersionParts = other.version.split("\\.");
for (int i = 0; i < Math.min(versionParts.length, otherVersionParts.length); i++) {
if (versionParts[i].length() == otherVersionParts[i].length()) {
int comparisonResult = versionParts[i].compareTo(otherVersionParts[i]);
if (comparisonResult == 0) {
continue;
} else {
return comparisonResult;
}
} else {
return versionParts[i].length() > otherVersionParts[i].length() ? 1 : -1;
}
}
if (versionParts.length > otherVersionParts.length) {
return 1;
} else if (versionParts.length < otherVersionParts.length) {
return -1;
} else {
return 0;
}
}
}
package com.zrqx.core.util.useragent;
/**
* Interaface that gets string and returns extrancted version
* @author alexr
*/
public interface VersionFetcher {
Version version(String str);
}
package com.zrqx.core.util.useragent;
import java.util.Collections;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Sometimes version of something is not written clearly in User-Agent string.
* However it is possible to extract version of other component that can be
* mapped to needed version. Concrete example is discovery of version of Safari
* browser by version of Webkit.
* @author alexr
*/
public class VersionFetcherFromMap extends PatternBasedVersionFetcher {
private final Map<String, Version> versions;
public VersionFetcherFromMap(Pattern pattern, Map<String, Version> versions) {
super(pattern);
this.versions = Collections.unmodifiableMap(versions);
}
protected Version createVersion(Matcher matcher) {
return versions.get(matcher.group(1));
}
}
package com.zrqx.core.vo.member;
import com.zrqx.core.enums.BooleanStatusEnum;
import com.zrqx.core.enums.member.RegisterTypeEnum;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 登录 vo
* @author lpf
* @date 2020-06-28
*/
@Data
@ApiModel(value = "LoginVo", description = "用户登录信息")
public class LoginVo {
@ApiModelProperty("y-token")
private String token;
/** @see com.zrqx.core.enums.BooleanStatusEnum */
@ApiModelProperty("判断用户是否存在 不存在0 存在1")
private String isExsit;
/** @see com.zrqx.core.enums.member.RegisterTypeEnum */
@ApiModelProperty("用户登录方式 默认:simple")
private String loginType;
public void setLoginType(RegisterTypeEnum registerTypeEnum) {
this.loginType = registerTypeEnum.getCode();
}
public void setIsExsit(String isExsit) {
this.isExsit = isExsit;
}
public void setIsExsit(BooleanStatusEnum statusEnum) {
this.isExsit = statusEnum.getCode();
}
}
package com.zrqx.core.vo.member;
import com.zrqx.core.enums.BooleanStatusEnum;
import com.zrqx.core.enums.member.RegisterTypeEnum;
import com.zrqx.core.model.member.Member;
import com.zrqx.core.util.datatype.UUIDUtil;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* member 存储到redis中的对象, 所有和用户依赖相关,可以添加此类的属性
* @author lpf
* @date 2020-06-28
*/
@Data
public class RedisMember {
@ApiModelProperty("用户基本信息")
private Member member;
@ApiModelProperty("用户登录信息")
private LoginVo loginVo;
@ApiModelProperty("用户是否可以重置密码")
private boolean canResetPassword;
public static RedisMember build(){
RedisMember redisMember = new RedisMember();
LoginVo loginVo = new LoginVo();
loginVo.setLoginType(RegisterTypeEnum.SIMPLE);
loginVo.setIsExsit(BooleanStatusEnum.YES);
loginVo.setToken(UUIDUtil.getUUID());
redisMember.setLoginVo(loginVo);
redisMember.setCanResetPassword(false);
return redisMember;
}
}
package com.zrqx.core.vo.member;
import com.zrqx.core.enums.member.RegisterTypeEnum;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @author lpf
* @date 2020-06-29
*/
@Data
public class ThirdLoginVo {
@ApiModelProperty("用户开放id,唯一")
private String openid;
@ApiModelProperty("昵称")
private String nickname;
@ApiModelProperty("头像")
private String headImgUrl;
@ApiModelProperty("第三方类型")
private RegisterTypeEnum type;
}
......@@ -99,5 +99,10 @@
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.1</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.zrqx.member.commons.redis;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import com.zrqx.core.exception.BaseException;
import com.zrqx.core.util.JsonUtil.JsonUtil;
import com.zrqx.core.util.datatype.StringUtils;
/**
* redis 基础操作类
* @author lpf
* @date 2019年10月29日上午9:21:31
*/
public abstract class BaseRedis {
private final static Logger log = LoggerFactory.getLogger(BaseRedis.class);
protected StringRedisTemplate stringRedisTemplate;
private final String SET_ERROR = "redis 存储信息时错误";
private final String GET_NULL_ERROR = "redis获取信息时为空;";
/** 默认失效时间 7天 */
protected final int DEFAULT_LOSE_TIME = 7;
/**
* redis模板类
* @param stringRedisTemplate
*/
protected abstract void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate);
/**
* 添加到redis
* @param token
* Key
* @param obj
* Value
* @param timeout
* 过期时间
* @param unit
* TimeUnitEnum 时间格式
* @throws IOException
*/
public void set(String token, Object obj, long timeout,TimeUnit unit) throws BaseException {
try {
stringRedisTemplate.opsForValue().set(token,fmtObj(obj),timeout,unit);
} catch (Exception e) {
this.exception(SET_ERROR, e);
}
}
public void set(String token, Object obj, long timeout) throws BaseException {
try {
stringRedisTemplate.opsForValue().set(token,fmtObj(obj),timeout,TimeUnit.SECONDS);
} catch (Exception e) {
this.exception(SET_ERROR, e);
}
}
public void set(String token,Object obj) throws BaseException{
try {
stringRedisTemplate.opsForValue().set(token,fmtObj(obj), 7, TimeUnit.DAYS);
} catch (Exception e) {
this.exception(SET_ERROR, e);
}
}
private void exception(String error, Exception e) throws BaseException{
log.error(error, e);
throw new BaseException(error, e);
}
public String fmtObj(Object obj) throws IOException {
return obj instanceof String ? obj.toString():JsonUtil.bean2Json(obj);
}
public Set<String> keys(String k) {
if (StringUtils.isBlank(k)) {
return new HashSet<String>();
}
return stringRedisTemplate.keys(k);
}
/**
* 获取全部keys
* @return
* @author lpf
* @date: 2019年10月29日 上午11:00:10
*/
public Set<String> keys(){
return this.keys("*");
}
/**
* 根据key删除redis中的数据
* @param key 不能为null
* @throws IOException
*/
public void delete(String key){
stringRedisTemplate.delete(key);
}
public void deletePattern(String key) {
Set<String> set = keys(key);
set.forEach(this :: delete);
}
/**
* 更换redis库
* @param num
* @author lpf
* @date: 2019年10月29日 上午9:46:39
*/
public void updateDatebase(int num) {
JedisConnectionFactory jedisConnectionFactory = (JedisConnectionFactory) stringRedisTemplate.getConnectionFactory();
jedisConnectionFactory.setDatabase(num);
stringRedisTemplate.setConnectionFactory(jedisConnectionFactory);
}
/**
* 查询key 的值
* @param key
* @return
* @author lpf
* @date: 2019年10月29日 上午9:49:53
*/
public String get(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
public <T> T get(String key, Class<T> clazz) {
String value = this.get(key);
if (StringUtils.isBlank(value)) {
String error = GET_NULL_ERROR + "key:" + key;
this.exception(error, new NullPointerException(error));
}
try {
return JsonUtil.json2Bean(value, clazz);
} catch (Exception e) {
e.printStackTrace();
this.exception(GET_NULL_ERROR + "解析JSON失败,value:"+ value + ";class:" + clazz, e);
}
return null;
}
public <T> List<T> getList(String key,Class<T> clazz){
String value = this.get(key);
if (StringUtils.isBlank(value)) {
String error = GET_NULL_ERROR + "key:" + key;
this.exception(error, new NullPointerException(error));
}
try {
return JsonUtil.json2List(value, clazz);
} catch (Exception e) {
this.exception(GET_NULL_ERROR + "解析JSON失败,value:"+ value + ";class:" + clazz, e);
}
return new ArrayList<>();
}
}
/**
* @author ray
* @date 2018年8月24日 下午3:29:56
*/
package com.zrqx.member.fg.captcha.commons.config;
public class QqLoginConfig {
/**
* appid
*/
public final static String APPID = "101239483";
//public final static String APPID = "101502595";
public final static String APPKEY="380e85587c92d5c77c1e5c6101c167fa";
//public final static String APPKEY="786496018f7747d51efe6311df644cd4";
/**
* 回调地址
*/
public final static String REDIRECTURI = "http://test16.zhongdianyun.com:8096";
//public final static String REDIRECTURI = "http%3a%2f%2frsks.class.com.cn%2f%23%2findex";
//public final static String REDIRECTURI = "http%3a%2f%2frsks.class.com.cn%2ffg%2findex.html%23%2flogin";
}
/**
* @author ray
* @date 2018年8月24日 下午4:44:24
*/
package com.zrqx.member.fg.captcha.commons.config;
public class WeChatLoginConfig {
/** appid 应用唯一标识 中软启信 */
public final static String APPID = "wx873ceb40c12d6e95";
/** 密钥AppSecret 中软启信 */
public final static String SECRET = "3d78b9b1a89ee9434e0d6afd944888f3";
/** 固定值 填写 authorization_code */
public final static String GRANT_TYPE = "authorization_code";
/** 固定值 填写code */
public final static String RESPONSE_TYPE = "code";
/** 固定值 填写snsapi_login */
public final static String SCOPE = "snsapi_login";
/** 回调域 */
public final static String REDIRECTURI = "http://test16.zhongdianyun.com";
}
package com.zrqx.member.fg.member.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.zrqx.core.components.captcha.form.CaptchaForm;
import com.zrqx.core.components.captcha.service.CaptchaValidateService;
import com.zrqx.core.enums.StatusEnum;
import com.zrqx.core.enums.captcha.CaptchaTypeEnum;
import com.zrqx.core.exception.BaseException;
import com.zrqx.core.form.AbstractLoginForm;
import com.zrqx.core.form.BaseLoginForm;
import com.zrqx.core.util.spring.SpringContextUtils;
import com.zrqx.core.vo.member.RedisMember;
import com.zrqx.member.commons.redis.Redis;
/**
* @author lpf
* @date 2020-06-28
*/
public abstract class BaseLoginServiceImpl<T> implements LoginService<T> {
private static final Logger log = LoggerFactory.getLogger(BaseLoginServiceImpl.class);
@Autowired
protected FgMemberService service;
@Autowired
private FgLoginLogService loginLogService;
@Autowired
private Redis redis;
@Autowired
private SpringContextUtils springContextUtils;
protected CaptchaValidateService getCaptchaValidateService(CaptchaForm form){
CaptchaValidateService service = springContextUtils.getEnumsBindBean(CaptchaTypeEnum.class, form.getType(), CaptchaValidateService.class);
return service;
}
/**
* 登录主逻辑
* @param t 前台提交参数
* @return
*/
@Override
public RedisMember login(T t) {
if (t instanceof AbstractLoginForm) {
CaptchaForm captchaForm = ((AbstractLoginForm) t).getCaptchaForm();
log.info("登录主逻辑-验证码验证form:{}", captchaForm);
// 验证码校验
getCaptchaValidateService(captchaForm).validate(captchaForm);
}
BaseLoginForm<T> form = new BaseLoginForm<>(t);
RedisMember redisMember = this.login(form);
// 验证用户是否被禁用
if (!StatusEnum.ENABLE.getCode().equals(redisMember.getMember().getStatus())) {
throw new BaseException("账号已被禁用,请联系管理员!");
}
loginLogService.insert(redisMember, form);
redis.setRedisMember(redisMember);
return redisMember;
}
protected RedisMember initRedisMember() {
return RedisMember.build();
}
/**
* 登录逻辑
* @param form 登录提交信息
* @return redis存放的会员信息
* @author lpf
* @date 2020-06-28 15:43
*/
protected abstract RedisMember login(BaseLoginForm<T> form);
}
package com.zrqx.member.fg.member.service;
import com.zrqx.core.form.BaseLoginForm;
import com.zrqx.core.model.member.LoginLog;
import com.zrqx.core.service.BaseService;
import com.zrqx.core.vo.member.RedisMember;
public interface FgLoginLogService extends BaseService<LoginLog, Integer> {
/**
......@@ -12,5 +14,11 @@ public interface FgLoginLogService extends BaseService<LoginLog, Integer> {
* @param channel 登录渠道 0 PC,1 WAP,2 Android,3 iOS
* @param description 描述
*/
void save(String account,String ip,Integer type,Integer channel,String description);
void save(String account,String ip,Integer type,String channel,String description);
/**
* 根据redisMember信息,登录信息 保存登录日志
* @param redisMember
* @param form
*/
void insert(RedisMember redisMember, BaseLoginForm form);
}
package com.zrqx.member.fg.member.service;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zrqx.core.form.BaseLoginForm;
import com.zrqx.core.mapper.BaseMapper;
import com.zrqx.core.model.member.LoginLog;
import com.zrqx.core.model.member.UserAgentInfo;
import com.zrqx.core.service.BaseServiceImpl;
import com.zrqx.core.util.IpUtil;
import com.zrqx.core.util.datatype.DateUtils;
import com.zrqx.core.vo.member.RedisMember;
import com.zrqx.member.fg.member.mapper.FgLoginLogMapper;
@Service
......@@ -18,7 +24,7 @@ public class FgLoginLogServiceImpl extends BaseServiceImpl<LoginLog,Integer> im
return mapper;
}
@Override
public void save(String account, String ip, Integer type, Integer channel,String description) {
public void save(String account, String ip, Integer type, String channel,String description) {
LoginLog ll = new LoginLog();
ll.setLoginAccount(account);
ll.setIp(ip);
......@@ -28,5 +34,23 @@ public class FgLoginLogServiceImpl extends BaseServiceImpl<LoginLog,Integer> im
ll.setCreateTime(DateUtils.getDate());
mapper.insert(ll);
}
@Override
public void insert(RedisMember redisMember, BaseLoginForm form) {
LoginLog entity = new LoginLog();
entity.setMemberId(redisMember.getMember().getId());
entity.setIp(IpUtil.getIp(form.getRequest()));
entity.setCreateTime(new Date());
entity.setPhone(redisMember.getMember().getPhone());
entity.setName(redisMember.getMember().getAccount());
entity.setRemark(redisMember.getLoginVo().getLoginType());
UserAgentInfo agentInfo = form.getAgentInfo();
entity.setChannel(agentInfo.getDeviceType());
entity.setDeviceType(agentInfo.getDeviceType());
entity.setBrowserName(agentInfo.getBrowserName());
entity.setBrowserType(agentInfo.getBrowserType());
entity.setBrowserVersion(agentInfo.getBrowserVersion());
entity.setManufacturer(agentInfo.getManufacturer());
entity.setOperatingSystemName(agentInfo.getOperatingSystemName());
super.insert(entity);
}
}
package com.zrqx.member.fg.member.service;
import java.util.Optional;
import com.zrqx.core.form.BaseLoginForm;
import com.zrqx.core.form.PhoneAbstractLoginForm;
import com.zrqx.core.form.RegisterFormAbstract;
import com.zrqx.core.form.ThirdLoginForm;
import com.zrqx.core.form.ThridPhoneFormAbstract;
import com.zrqx.core.form.member.fg.permissions.LoginMemberInfo;
import com.zrqx.core.model.member.Member;
import com.zrqx.core.service.BaseService;
import com.zrqx.core.vo.member.RedisMember;
import com.zrqx.core.vo.member.ThirdLoginVo;
import com.zrqx.core.vo.member.fg.personalcenter.MemberInfo;
public interface FgMemberService extends BaseService<Member, Integer> {
......@@ -57,4 +66,91 @@ public interface FgMemberService extends BaseService<Member, Integer> {
*/
boolean isExistByPhone(Integer id, String phone);
/**
* 查询账号或手机号为 text的用户,用户可能存在也可能不存在
* @param text
* @return
*/
Optional<Member> getByAccountOrPhone(String text);
/**
* 根据手机号 注册用户
* @param form
* @return
*/
Member insertByPhone(BaseLoginForm<PhoneAbstractLoginForm> form);
/**
* 根据qqkey查询用户,用户可能存在可能不存在
* @param key
* @return
*/
Optional<Member> getByQqKey(String key);
/**
* 根据wechartkey查询用户,用户可能存在可能不存在
* @param key
* @return
*/
Optional<Member> getByWechatkey(String key);
/**
* 根据第三方信息保存用户
* @param form
* @param thirdLoginVo
* @return
*/
Member insertByThird(BaseLoginForm<ThirdLoginForm> form, ThirdLoginVo thirdLoginVo);
/**
* 根据注册信息保存用户
* @param form
* @return
*/
Member insertByRegister(BaseLoginForm<RegisterFormAbstract> form);
/**
* 合并第三方账号
* @param form
* @return
*/
void updateByThird(ThridPhoneFormAbstract form);
/**
* 校验账号是否存在,存在抛出异常
* @param account
*/
void validateAccount(String account);
/**
* 校验机构码
* @param code
*/
void validateCode(String code);
/**
* 验证手机号对应的账号是否被禁用,找不到对应的账号不抛异常
* 异常1:账号已被禁用,请联系管理员!
* @param phone
* @return
*/
Optional<Member> validatePhone(String phone);
/**
* 用户重置密码-手机号验证码校验,校验成功后,生成对应的RedisMember,存储登录信息(临时),重置密码完成后,删除登录信息
* 异常1:账号已被禁用,请联系管理员!
* 异常2:手机号未注册
* @param form
* @return
*/
RedisMember validateResetPassword(PhoneAbstractLoginForm form);
/**
* 验证手机号对应的账号
* 异常1:账号已被禁用,请联系管理员!
* 异常2:手机号未注册
* @param phone
* @return
*/
Member validateResetPasswordPhone(String phone);
}
package com.zrqx.member.fg.member.service;
import com.zrqx.core.vo.member.RedisMember;
/**
* 登录注册service
* @author lpf
* @date 2020-06-28
*/
public interface LoginService<T> {
/**
* 登录
* @param t
* @return
*/
RedisMember login(T t);
}
\ No newline at end of file
package com.zrqx.member.fg.member.service;
import java.util.Optional;
import org.springframework.stereotype.Service;
import com.zrqx.core.enums.BooleanStatusEnum;
import com.zrqx.core.enums.member.RegisterTypeEnum;
import com.zrqx.core.form.BaseLoginForm;
import com.zrqx.core.form.PhoneAbstractLoginForm;
import com.zrqx.core.model.member.Member;
import com.zrqx.core.vo.member.RedisMember;
/**
* 手机号快捷登录
* @author lpf
* @date 2020-06-28
*/
@Service
public class PhoneLoginServiceImpl extends BaseLoginServiceImpl<PhoneAbstractLoginForm>{
@Override
protected RedisMember login(BaseLoginForm<PhoneAbstractLoginForm> form) {
// 根据手机号查询账号是否存在
final String phone = form.getReqForm().getCaptchaForm().getPhone();
Optional<Member> memberOptional = service.getByAccountOrPhone(phone);
RedisMember redisMember = super.initRedisMember();
redisMember.getLoginVo().setLoginType(RegisterTypeEnum.PHONE);
Member m = memberOptional.orElseGet(() -> {
redisMember.getLoginVo().setIsExsit(BooleanStatusEnum.NO);
redisMember.setCanResetPassword(true);
return service.insertByPhone(form);
});
redisMember.setMember(m);
return redisMember;
}
}
package com.zrqx.member.fg.member.service;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zrqx.core.enums.BooleanStatusEnum;
import com.zrqx.core.enums.member.RegisterTypeEnum;
import com.zrqx.core.exception.BaseException;
import com.zrqx.core.form.BaseLoginForm;
import com.zrqx.core.form.ThirdLoginForm;
import com.zrqx.core.model.member.Member;
import com.zrqx.core.util.HttpsUtils;
import com.zrqx.core.vo.member.RedisMember;
import com.zrqx.core.vo.member.ThirdLoginVo;
import com.zrqx.member.fg.captcha.commons.config.QqLoginConfig;
/**
* @author lpf
* @date 2020-06-29
*/
@Service("qqLoginServiceImpl")
public class QqLoginServiceImpl extends BaseLoginServiceImpl<ThirdLoginForm>{
@Override
protected RedisMember login(BaseLoginForm<ThirdLoginForm> form) {
ThirdLoginVo thirdLoginVo = this.query(form.getReqForm().getCode());
thirdLoginVo.setType(RegisterTypeEnum.QQ);
Optional<Member> memberOptional = service.getByQqKey(thirdLoginVo.getOpenid());
RedisMember redisMember = super.initRedisMember();
redisMember.getLoginVo().setLoginType(RegisterTypeEnum.QQ);
Member m = memberOptional.orElseGet(() -> {
redisMember.getLoginVo().setIsExsit(BooleanStatusEnum.NO);
redisMember.setCanResetPassword(true);
return service.insertByThird(form, thirdLoginVo);
});
redisMember.setMember(m);
return redisMember;
}
private ThirdLoginVo query(String code){
String appid= QqLoginConfig.APPID;
String appkey= QqLoginConfig.APPKEY;
String redirectUri = QqLoginConfig.REDIRECTURI;
//根据code获取Access Token
String param1="grant_type=authorization_code&client_id="+appid+"&client_secret="+appkey+"&code="+code+"&redirect_uri="+ redirectUri;
String result1= HttpsUtils.sendGet("https://graph.qq.com/oauth2.0/token", param1);
//正确返回形式 : access_token=986A0E8DE045BFD2B94689F6D7F3CFCD&expires_in=7776000&refresh_token=E476F1B911CE70E1F0C1A9B84EE181A7
//错误返回形式: callback( {"error":100019,"error_description":"code to access token error"} );
//判断是否是错误返回
String callbackKey = "callback";
if(result1.indexOf(callbackKey)>-1){
String newResult1=result1.substring(result1.indexOf("(")+1, result1.lastIndexOf(")"));
JSONObject object1=(JSONObject) JSON.parse(newResult1);
throw new BaseException(object1.get("error").toString());
}
//正确返回解析出 access_token
Map<String,String> map= this.splitBody(result1);
String accessToken=map.get("access_token");
//根据 Access Token 获取openid
String param2="access_token="+accessToken;
String result2=HttpsUtils.sendGet("https://graph.qq.com/oauth2.0/me", param2);
String newResult2=result2.substring(result2.indexOf("(")+1, result2.lastIndexOf(")"));
JSONObject object2=(JSONObject)JSON.parse(newResult2);
String openid=object2.get("openid").toString();
//获得用户详情
String param="access_token="+accessToken+"&openid="+openid+"&oauth_consumer_key="+appid;
String result=HttpsUtils.sendGet("https://graph.qq.com/user/get_user_info", param);
JSONObject object=(JSONObject)JSON.parse(result);
//用户昵称
String nickname=object.get("nickname").toString();
//用户头像
String headimgurl=object.get("figureurl_qq_1").toString();
ThirdLoginVo user=new ThirdLoginVo();
user.setOpenid(openid);
user.setNickname(nickname);
user.setHeadImgUrl(headimgurl);
return user;
}
Map<String, String> splitBody(String body){
Map<String,String> map=new HashMap<String,String>(16);
if(StringUtils.isNotBlank(body)){
//将 access_token=986A0E8DE045BFD2B94689F6D7F3CFCD&expires_in=7776000&refresh_token=E476F1B911CE70E1F0C1A9B84EE181A7形式参数分割成数组
String[] arr=body.split("&");
//将=左边作为key,=右边作为value
for(String str:arr){
String[] arr1=str.split("=");
map.put(arr1[0], arr1[1]);
}
}
return map;
}
}
package com.zrqx.member.fg.member.service;
import org.springframework.stereotype.Service;
import com.zrqx.core.form.BaseLoginForm;
import com.zrqx.core.form.RegisterFormAbstract;
import com.zrqx.core.model.member.Member;
import com.zrqx.core.vo.member.RedisMember;
/**
* @author lpf
* @date 2020-06-30
*/
@Service
public class RegisterLoginServiceImpl extends BaseLoginServiceImpl<RegisterFormAbstract> {
@Override
protected RedisMember login(BaseLoginForm<RegisterFormAbstract> form) {
service.validateAccount(form.getReqForm().getAccount());
service.validateCode(form.getReqForm().getCode());
RedisMember redisMember = super.initRedisMember();
Member m = service.insertByRegister(form);
redisMember.setCanResetPassword(true);
redisMember.setMember(m);
return redisMember;
}
}
package com.zrqx.member.fg.member.service;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.zrqx.core.exception.BaseException;
import com.zrqx.core.form.BaseLoginForm;
import com.zrqx.core.form.SimpleAbstractLoginForm;
import com.zrqx.core.model.member.Member;
import com.zrqx.core.vo.member.RedisMember;
/**
* 账号密码登录
* @author lpf
* @date 2020-06-28
*/
@Service
public class SimpleLoginServiceImpl extends BaseLoginServiceImpl<SimpleAbstractLoginForm>{
@Override
protected RedisMember login(BaseLoginForm<SimpleAbstractLoginForm> form) {
Optional<Member> memberOptional = service.getByAccountOrPhone(form.getReqForm().getAccount());
final BaseException exception = new BaseException("账号或密码错误");
Member member = memberOptional.orElseThrow(() -> exception);
if (StringUtils.isEmpty(member.getPassword())) {
throw exception;
}
if (!member.getPassword().equalsIgnoreCase(form.getReqForm().getPassword())) {
throw exception;
}
RedisMember redisMember = super.initRedisMember();
redisMember.setMember(member);
return redisMember;
}
}
package com.zrqx.member.fg.member.service;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zrqx.core.enums.BooleanStatusEnum;
import com.zrqx.core.enums.ResponseCodeEnum;
import com.zrqx.core.enums.member.RegisterTypeEnum;
import com.zrqx.core.exception.BaseException;
import com.zrqx.core.form.BaseLoginForm;
import com.zrqx.core.form.ThirdLoginForm;
import com.zrqx.core.model.member.Member;
import com.zrqx.core.util.HttpsUtils;
import com.zrqx.core.vo.member.RedisMember;
import com.zrqx.core.vo.member.ThirdLoginVo;
import com.zrqx.member.fg.captcha.commons.config.WeChatLoginConfig;
/**
* @author lpf
* @date 2020-06-29
*/
@Service
public class WechatLoginServiceImpl extends BaseLoginServiceImpl<ThirdLoginForm>{
private static final Logger log = LoggerFactory.getLogger(WechatLoginServiceImpl.class);
@Override
protected RedisMember login(BaseLoginForm<ThirdLoginForm> form) {
ThirdLoginVo thirdLoginVo = this.query(form.getReqForm().getCode());
thirdLoginVo.setType(RegisterTypeEnum.WECHAT);
Optional<Member> memberOptional = service.getByWechatkey(thirdLoginVo.getOpenid());
RedisMember redisMember = super.initRedisMember();
redisMember.getLoginVo().setLoginType(RegisterTypeEnum.WECHAT);
Member m = memberOptional.orElseGet(() -> {
redisMember.getLoginVo().setIsExsit(BooleanStatusEnum.NO);
redisMember.setCanResetPassword(true);
return service.insertByThird(form, thirdLoginVo);
});
redisMember.setMember(m);
return redisMember;
}
private ThirdLoginVo query(String code){
String appid="appid="+ WeChatLoginConfig.APPID;
String secret="&secret="+WeChatLoginConfig.SECRET;
String code1="&code="+code;
String grantType="&grant_type="+WeChatLoginConfig.GRANT_TYPE;
//调用微信接口获得openid和access_token
String param=appid+secret+code1+grantType;
String result= HttpsUtils.sendGet("https://api.weixin.qq.com/sns/oauth2/access_token", param);
JSONObject object = (JSONObject) JSON.parse(result);
log.info("调用微信接口获得openid和access_token result:{}",result);
//判断接口是否调用成功
String errorKey = "errcode";
if(object.containsKey(errorKey)){
throw new BaseException(ResponseCodeEnum.EXCEPTION.getCode(),object.get(errorKey).toString());
}
//唯一标识用户的 openId
String openId=object.get("openid").toString();
//凭证
String accessToken=object.get("access_token").toString();
//调用微信接口获得用户信息
String param1="access_token="+accessToken+"&openid="+openId;
String result1=HttpsUtils.sendGet("https://api.weixin.qq.com/sns/userinfo", param1);
JSONObject object1=(JSONObject)JSON.parse(result1);
log.info("微信获取用户信息result:{}",result1);
//判断接口是否调用成功
if(object1.containsKey(errorKey)){
throw new BaseException(ResponseCodeEnum.EXCEPTION.getCode(),object1.get(errorKey).toString());
}
//用户昵称
String nickname=object1.get("nickname").toString();
//用户头像
String headimgurl=object1.get("headimgurl").toString();
ThirdLoginVo user=new ThirdLoginVo();
user.setOpenid(openId);
user.setNickname(nickname);
user.setHeadImgUrl(headimgurl);
return user;
}
}
package com.zrqx.member.fg.permissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zrqx.core.constant.member.MemberRequestPath;
import com.zrqx.core.enums.BooleanStatusEnum;
import com.zrqx.core.exception.BaseException;
import com.zrqx.core.form.PhoneAbstractLoginForm;
import com.zrqx.core.form.PhonePassordForm;
import com.zrqx.core.form.RegisterFormAbstract;
import com.zrqx.core.form.ResetPasswordForm;
import com.zrqx.core.form.SimpleAbstractLoginForm;
import com.zrqx.core.form.ThirdLoginForm;
import com.zrqx.core.form.ThridPhoneFormAbstract;
import com.zrqx.core.model.member.Member;
import com.zrqx.core.util.datatype.StringUtils;
import com.zrqx.core.util.response.CallBack;
import com.zrqx.core.vo.member.LoginVo;
import com.zrqx.core.vo.member.RedisMember;
import com.zrqx.member.commons.redis.Redis;
import com.zrqx.member.fg.member.service.FgMemberService;
import com.zrqx.member.fg.member.service.LoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
/**
*
* @author lpf
* @date 2020-06-28
*/
@RestController
@RequestMapping(MemberRequestPath.FG +MemberRequestPath.LOGIN)
@Api(description = "前台-登录注册")
public class FgLoginController {
private static final Logger log = LoggerFactory.getLogger(FgLoginController.class);
@Autowired
@Qualifier("simpleLoginServiceImpl")
private LoginService simpleLoginService;
@Autowired
@Qualifier("phoneLoginServiceImpl")
private LoginService phoneLoginSerivce;
@Autowired
@Qualifier("qqLoginServiceImpl")
private LoginService qqLoginService;
@Autowired
@Qualifier("wechatLoginServiceImpl")
private LoginService wechatLoginService;
@Autowired
@Qualifier("registerLoginServiceImpl")
private LoginService registerLoginService;
@Autowired
private Redis redis;
@Autowired
private FgMemberService service;
@ApiOperation("手机号+验证码快捷登录")
@PostMapping("/phone")
public CallBack<RedisMember> loginPhone(@RequestBody PhoneAbstractLoginForm form) {
return CallBack.success(phoneLoginSerivce.login(form));
}
@ApiOperation("账号密码登录")
@PostMapping("/login")
public CallBack<RedisMember> login(@RequestBody SimpleAbstractLoginForm form) {
if (StringUtils.isEmpty(form.getAccount())) {
throw new BaseException("账号不能为空");
}
if (StringUtils.isEmpty(form.getPassword())) {
throw new BaseException("密码不能为空");
}
return CallBack.success(simpleLoginService.login(form));
}
@ApiOperation("qq登录")
@GetMapping("/qq")
public CallBack<RedisMember> loginQq(ThirdLoginForm form) {
if (StringUtils.isEmpty(form.getCode())) {
throw new BaseException("code不能为空");
}
return CallBack.success(qqLoginService.login(form));
}
@ApiOperation("微信登录")
@GetMapping("/wechat")
public CallBack<RedisMember> loginWechat(ThirdLoginForm form) {
if (StringUtils.isEmpty(form.getCode())) {
throw new BaseException("code不能为空");
}
return CallBack.success(wechatLoginService.login(form));
}
@ApiOperation("手机号首次登录-设置密码")
@PostMapping("/phone/reset-password")
public CallBack<?> resetPhonePassword(@RequestBody PhonePassordForm form) {
if (StringUtils.isEmpty(form.getPassword())) {
throw new BaseException("密码不能为空");
}
RedisMember redisMember = redis.getNotNullRedisMember();
LoginVo loginVo = redisMember.getLoginVo();
if (loginVo == null || BooleanStatusEnum.YES.getCode().equals(loginVo.getIsExsit())){
throw new BaseException("用户不为首次登录,无法重置密码");
}
Member member = redisMember.getMember();
Member entity = service.notNull(member.getId());
entity.setPassword(form.getPassword());
boolean result = service.updateByPrimaryKey(entity);
if (result) {
return CallBack.success();
}
log.error("用户重置密码失败,form:{}",form);
return CallBack.fail("用户重置密码失败,请联系管理员");
}
@ApiOperation("第三方首次登录-设置手机号")
@PostMapping("/third/reset-phone")
public CallBack<?> resetThirdPhone(@RequestBody ThridPhoneFormAbstract form){
service.updateByThird(form);
return CallBack.success();
}
@ApiOperation("异步校验手机号,账号是否被禁用提示 “账号已被禁用,请联系管理员”")
@GetMapping("/validate/phone")
public CallBack<?> validatePhone(String phone) {
service.validatePhone(phone);
return CallBack.success();
}
@ApiOperation("用户名异步校验用户是否已被注册, 提示 “用户名已存在”")
@GetMapping("/validate/account")
public CallBack<?> validateAccount(String account) {
service.validateAccount(account);
return CallBack.success();
}
@ApiOperation("异步验证机构码是否正确, “请输入正确的机构码”")
@GetMapping("/validate/code")
public CallBack<?> validateCode(String code) {
service.validateCode(code);
return CallBack.success();
}
@ApiOperation("注册并登录")
@PostMapping("/register")
public CallBack<RedisMember> loginRegister(@RequestBody RegisterFormAbstract form) {
return CallBack.success(registerLoginService.login(form));
}
@ApiOperation("用户重置密码-手机验证,查询手机不存在提示“手机号未注册”,账号是否被禁用提示 “账号已被禁用,请联系管理员”")
@GetMapping("/validate/reset/phone")
public CallBack<?> validateResetPasswordPhone(String phone) {
service.validateResetPasswordPhone(phone);
return CallBack.success();
}
@ApiOperation("用户重置密码-手机短信验证")
@PostMapping("/validate/reset-pass")
public CallBack<RedisMember> validateResetPassword(@RequestBody PhoneAbstractLoginForm form) {
return CallBack.success(service.validateResetPassword(form));
}
@ApiOperation("用户重置密码")
@PostMapping("/reset-pass")
public CallBack<?> resetPassword(@RequestBody ResetPasswordForm form) {
if (StringUtils.isEmpty(form.getToken())) {
throw new BaseException("token is not null");
}
if (StringUtils.isEmpty(form.getPassword())) {
throw new BaseException("请输入密码");
}
if (StringUtils.isEmpty(form.getAgain())) {
throw new BaseException("请再次确认密码");
}
if (!form.getAgain().equals(form.getPassword())) {
throw new BaseException("密码输入不一致");
}
RedisMember redisMember = redis.getRedisMember(form.getToken());
if (redisMember == null || redisMember.getMember() == null) {
throw new BaseException("fg用户不存在");
}
if (!redisMember.isCanResetPassword()) {
throw new BaseException("用户无权限重置密码");
}
Member m = redisMember.getMember();
Member entity = service.notNull(m.getId());
entity.setPassword(form.getPassword());
boolean result = service.updateByPrimaryKey(entity);
if (result) {
redis.delete(form.getToken());
return CallBack.success();
}
log.error("用户重置密码失败,form:{},redismember:{}", form, redisMember);
return CallBack.fail("用户重置密码失败");
}
}
package com.zrqx.member.fg.permissions;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
......@@ -30,13 +27,9 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;
import tk.mybatis.mapper.entity.Example;
import com.zrqx.core.constant.member.MemberRequestPath;
import com.zrqx.core.enums.member.ChannelEnum;
import com.zrqx.core.exception.BaseException;
import com.zrqx.core.form.member.fg.permissions.BindForm;
import com.zrqx.core.form.member.fg.permissions.LoginForm;
import com.zrqx.core.form.member.fg.permissions.LoginMemberInfo;
import com.zrqx.core.form.member.fg.permissions.SaveOMemberForm;
......@@ -45,6 +38,7 @@ import com.zrqx.core.form.member.fg.permissions.SavePMemberForm;
import com.zrqx.core.form.member.fg.permissions.UpdatePasswordForm;
import com.zrqx.core.form.member.fg.permissions.WxLoginForm;
import com.zrqx.core.form.third.sdksms.SdkSmsForm;
import com.zrqx.core.form.third.sms.SmsForm;
import com.zrqx.core.model.member.Member;
import com.zrqx.core.model.member.Organ;
import com.zrqx.core.model.member.OrganMember;
......@@ -61,6 +55,7 @@ import com.zrqx.core.util.response.CallBack;
import com.zrqx.member.commons.redis.Redis;
import com.zrqx.member.fg.client.third.QQLoginClient;
import com.zrqx.member.fg.client.third.SdkSmsClient;
import com.zrqx.member.fg.client.third.SmsClient;
import com.zrqx.member.fg.client.third.WeChatLoginClient;
import com.zrqx.member.fg.member.service.FgLoginLogService;
import com.zrqx.member.fg.member.service.FgMemberService;
......@@ -68,6 +63,11 @@ import com.zrqx.member.fg.omember.service.FgOrganMemberService;
import com.zrqx.member.fg.organ.service.FgOrganService;
import com.zrqx.member.fg.pmember.service.FgPersonalMemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import sun.misc.BASE64Encoder;
import tk.mybatis.mapper.entity.Example;
/**
* 前台登录与注册Controller
*/
......@@ -83,6 +83,8 @@ public class FgPermissionsController {
@Autowired
private SdkSmsClient sdkSmsClient;
@Autowired
private SmsClient smsClient;
@Autowired
private FgMemberService mService;
@Autowired
private FgPersonalMemberService pmService;
......@@ -155,7 +157,7 @@ public class FgPermissionsController {
}*/
String token = "";
if(info.getLevel().equals(2)){
/*if(info.getLevel().equals(2)){
List<String> keys = redis.getAllToken();
if(!keys.isEmpty()){
List<String> keyList = new ArrayList<String>();
......@@ -172,7 +174,7 @@ public class FgPermissionsController {
token = MD5Util.getEncoderByMd5(m.getAccount()) + "-" + info.getOrganId();
}else{
token = MD5Util.getEncoderByMd5(m.getAccount());
}
}*/
info.setToken(token);
redis.set(token, info);
llService.save(form.getAccount(), ip, 1, form.getChannel(), "账号登录");
......@@ -338,12 +340,12 @@ public class FgPermissionsController {
redis.set(token, info);
return CallBack.success(true);
}
@ApiOperation(value = "前台用户登出", notes = "前台用户登出")
/*@ApiOperation(value = "前台用户登出", notes = "前台用户登出")
@GetMapping(value = MemberRequestPath.LOGOUT)
public CallBack<Boolean> logout() throws IOException {
redis.delete(Redis.getFgToken());
return CallBack.success(true);
}
}*/
@ApiOperation(value = "查询会员账号是否被注册", notes = "查询会员账号是否存在-普通用户和机构用户 共用此接口 0:可用; 99:已被注册;")
@GetMapping(value = MemberRequestPath.ISEXIST)
public CallBack<Boolean> isExistByAccount(Integer id, String account) {
......@@ -405,7 +407,7 @@ public class FgPermissionsController {
String token = MD5Util.getEncoderByMd5(m.getAccount());
info.setToken(token);
redis.set(token, info);
llService.save(form.getAccount(), ip, 1, ChannelEnum.Channel_0.getCode(), "账号登录");
llService.save(form.getAccount(), ip, 1, ChannelEnum.Channel_0.getCode().toString(), "账号登录");
return CallBack.success(info);
}
@ApiOperation(value = "机构用户注册", notes = "0:成功;12:该机构已过期;13:该机构已过期;14:该机构可使用次数不足,请从新发送;99:已存在;")
......@@ -449,7 +451,7 @@ public class FgPermissionsController {
String token = MD5Util.getEncoderByMd5(m.getAccount());
info.setToken(token);
redis.set(token, info);
llService.save(form.getAccount(), ip, 1, ChannelEnum.Channel_0.getCode(), "账号登录");
llService.save(form.getAccount(), ip, 1, ChannelEnum.Channel_0.getCode().toString(), "账号登录");
return CallBack.success(info);
}
@ApiOperation(value = "发送手机短信 注册时使用", notes = "0:成功;15:该手机号已被注册;16:60s内不能再次发送;17:当天注册发送验证码超过10次;18:短信验证码发送失败;")
......@@ -489,13 +491,13 @@ public class FgPermissionsController {
return CallBack.success("发送成功"+code);
}
@ApiOperation(value = "发送手机短信 登录时使用", notes = "0:成功;16:60s内不能再次发送;;18:短信验证码发送失败;")
/*@ApiOperation(value = "发送手机短信 登录时使用", notes = "0:成功;16:60s内不能再次发送;;18:短信验证码发送失败;")
@GetMapping(value = MemberRequestPath.LOGIN + MemberRequestPath.CODE)
public CallBack<String> loginCode(String phone) throws Exception{
/* if(!mService.isExistByPhone(null, phone)) {
if(!mService.isExistByPhone(null, phone)) {
throw new BaseException(99,"手机号未注册");
}*/
}
String sendTime = phone+"login";
if(redis.get(sendTime) != null) {
throw new BaseException(16,"60s内不能再次发送");
......@@ -512,8 +514,29 @@ public class FgPermissionsController {
throw new BaseException(18,"短信验证码发送失败");
}
return CallBack.success("发送成功"+code);
} */
@ApiOperation(value = "发送手机短信 登录时使用", notes = "0:成功;16:60s内不能再次发送;;18:短信验证码发送失败;")
@GetMapping(value = MemberRequestPath.LOGIN + MemberRequestPath.CODE)
public CallBack<String> loginCode(String phone) throws Exception{
String sendTime = phone+"login";
/* if(redis.get(sendTime) != null) {
throw new BaseException(16,"60s内不能再次发送");
}*/
SmsForm ssf = new SmsForm();
ssf.setPhone(phone);
String code = PasswordUtil.createPassword(6, 1);
ssf.setCode(code);
ssf.setType(3);
String sms = smsClient.sendSms(ssf);
if(sms!=null){
redis.set(phone, code,60*5,TimeUnit.SECONDS);
redis.set(sendTime, "60", 60);
}else{
throw new BaseException(18,"短信验证码发送失败");
}
return CallBack.success("发送成功"+code);
}
@ApiOperation(value = "重置密码-1 发送手机短信", notes = "0:成功;16:60s内不能再次发送;18:短信验证码发送失败;")
@GetMapping(value = MemberRequestPath.PASSWORD + MemberRequestPath.SENDMESSAGE)
public CallBack<String> resetPassword1(String phone) throws Exception{
......@@ -524,12 +547,13 @@ public class FgPermissionsController {
if(redis.get(sendTime) != null) {
throw new BaseException(16,"60s内不能再次发送");
}
SdkSmsForm ssf = new SdkSmsForm();
ssf.setMobile(phone);
SmsForm ssf = new SmsForm();
ssf.setPhone(phone);
String code = PasswordUtil.createPassword(6, 1);
ssf.setContent("您的验证码是:"+code+",在5分钟内有效。如非本人操作请忽略本短信。");
CallBack<String> sms = sdkSmsClient.send(ssf);
if(sms!=null && sms.isStatus()){
ssf.setCode(code);
ssf.setType(6);
String sms = smsClient.sendSms(ssf);
if(sms!=null ){
redis.set(phone, code,60*5,TimeUnit.SECONDS);
redis.set(sendTime, "60", 60);
}else{
......
......@@ -89,7 +89,7 @@ public class PersonalCenterConteroller {
@ApiOperation(value = "个人信息-修改", notes = "0:成功;")
@PostMapping(value = MemberRequestPath.UPDATE + MemberRequestPath.MEMBER)
public CallBack<String> updateMember(@RequestBody UpdateMemberForm form) {
LoginMemberInfo memberInfo = redis.getMember();
Member memberInfo = redis.getMember();
//判断是否是专家用户
Member member = new Member();
member.setId(memberInfo.getId());
......@@ -108,12 +108,8 @@ public class PersonalCenterConteroller {
pm.setId(memberInfo.getId());
mService.updateByPrimaryKeySelective(member);
pmService.updateByPrimaryKeySelective(pm);
try {
BeanUtils.copyPropertiesIgnoreNull(form, memberInfo, form);
redis.set(memberInfo.getToken(), memberInfo);
} catch (IOException e) {
e.printStackTrace();
}
BeanUtils.copyPropertiesIgnoreNull(form, memberInfo, form);
redis.set(memberInfo.getToken(), memberInfo);
}
return CallBack.success("");
}
......@@ -128,8 +124,8 @@ public class PersonalCenterConteroller {
*/
@ApiOperation(value = "账户安全-信息查询", notes = "0:成功;")
@GetMapping(value = MemberRequestPath.GET + MemberRequestPath.SAFEINFO)
public CallBack<LoginMemberInfo> getInfo() {
LoginMemberInfo memberInfo = redis.getMember();
public CallBack<Member> getInfo() {
Member memberInfo = redis.getMember();
return CallBack.success(memberInfo);
}
......@@ -170,7 +166,7 @@ public class PersonalCenterConteroller {
throw new BaseException(1, "验证码错误");
}
redis.delete(form.getPhone());
LoginMemberInfo memberInfo = redis.getMember();
Member memberInfo = redis.getMember();
// 修改手机号
Member m = new Member();
m.setId(memberInfo.getId());
......@@ -185,7 +181,7 @@ public class PersonalCenterConteroller {
@ApiOperation(value = "发送手机短信", notes = "0:成功;16:60s内不能再次发送;17:当天注册发送验证码超过10次;18:短信验证码发送失败;")
@GetMapping(value = MemberRequestPath.CODE_PHONE)
public CallBack<String> code(String phone) throws Exception {
LoginMemberInfo memberInfo = redis.getMember();
Member memberInfo = redis.getMember();
if(phone.equals(memberInfo.getPhone())) {
throw new BaseException(15, "不能修改成当前手机号");
}
......@@ -224,7 +220,7 @@ public class PersonalCenterConteroller {
@ApiOperation(value = "账户安全-解除绑定 1:qq;2:微信", notes = "0:成功;")
@PostMapping(value = MemberRequestPath.UNBIND + "/{type}")
public CallBack<String> unbind(@PathVariable("type") int type) throws IOException {
LoginMemberInfo memberInfo = redis.getMember();
Member memberInfo = redis.getMember();
Member member = new Member();
member.setId(memberInfo.getId());
if (type == 1) {
......@@ -247,7 +243,7 @@ public class PersonalCenterConteroller {
if (StringUtils.isBlank(form.getQqKey()) && StringUtils.isBlank(form.getWechatKey())) {
throw new BaseException(9, "第三方账号不能为空");
}
LoginMemberInfo memberInfo = redis.getMember();
Member memberInfo = redis.getMember();
Member member = new Member();
member.setId(memberInfo.getId());
if (StringUtils.isNotBlank(form.getQqKey())) {
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论