Commit a2c37855 authored by Administrator's avatar Administrator

Merge branch 'staging' into 'master'

Staging

See merge request !32
parents 22aa121d 1421c42b
......@@ -31,7 +31,7 @@
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.4.0.RELEASE</version>
<version>2.4.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security.oauth.boot/spring-security-oauth2-autoconfigure -->
<dependency>
......@@ -168,6 +168,14 @@
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency>
<!-- https://mvnrepository.com/artifact/ch.ethz.ganymed/ganymed-ssh2 -->
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>262</version>
</dependency>
</dependencies>
<build>
......
package com.edgec.browserbackend;
import com.mongodb.MongoClient;
import net.javacrumbs.shedlock.core.LockProvider;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.convert.Jsr310Converters;
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.provider.token.AuthenticationKeyGenerator;
import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
......@@ -19,6 +31,15 @@ import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
@SpringBootApplication
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableScheduling
......@@ -92,4 +113,68 @@ public class BrowserBackendApplication {
// @Value("${server.port}")
// private Integer httpsPort;
@Bean
public AuthenticationKeyGenerator authenticationKeyGenerator() {
return new DefaultAuthenticationKeyGenerator();
}
@Configuration
static class CustomConversionsConfig {
@Autowired
ApplicationContext context;
@Bean
public MongoCustomConversions customConversions() {
List<Converter<?, ?>> converters = new ArrayList<>();
converters.addAll(Jsr310Converters.getConvertersToRegister());
converters.add(BrowserBackendApplication.CustomConversionsConfig.DateToZonedDateTimeConverter.INSTANCE);
converters.add(BrowserBackendApplication.CustomConversionsConfig.ZonedDateTimeToDateConverter.INSTANCE);
return new MongoCustomConversions(converters);
}
enum LocalDateToStringConverter implements Converter<LocalDate, String> {
INSTANCE;
@Override
public String convert(LocalDate source) {
return source.toString();
}
}
enum StringToLocalDateConverter implements Converter<String, LocalDate> {
INSTANCE;
@Override
public LocalDate convert(String source) {
return LocalDate.parse(source);
}
}
enum DateToZonedDateTimeConverter implements Converter<Date, ZonedDateTime> {
INSTANCE;
@Override
public ZonedDateTime convert(Date source) {
return ZonedDateTime.ofInstant(source.toInstant(), ZoneId.of("UTC"));
}
}
enum ZonedDateTimeToDateConverter implements Converter<ZonedDateTime, Date> {
INSTANCE;
@Override
public Date convert(ZonedDateTime source) {
return Date.from(source.toInstant());
}
}
}
}
......@@ -8,6 +8,8 @@ public interface AccountRepositoryCustom {
List<String> findInName(String[] name);
List<String> findParents(List<String> names);
void updateRealNameAndIdCard(String username, String realName, String idCard);
Account findByPromotion(String code);
......
......@@ -9,6 +9,7 @@ import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.MatchOperation;
import org.springframework.data.mongodb.core.aggregation.ProjectionOperation;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Update;
import java.util.ArrayList;
......@@ -41,6 +42,19 @@ public class AccountRepositoryCustomImpl implements AccountRepositoryCustom {
return accountTelephones;
}
@Override
public List<String> findParents(List<String> names) {
Document query = new Document();
Document fields = new Document();
fields.put("name", 1);
BasicQuery basicQuery = new BasicQuery(query, fields);
Criteria criteria = new Criteria();
basicQuery.addCriteria(criteria.orOperator(where("name").in(names)));
return null;
}
@Override
public void updateRealNameAndIdCard(String username, String realName, String idCard) {
Document doc = new Document();
......
......@@ -24,4 +24,7 @@ public interface PaymentService {
boolean alipayWithdraw(String username, String account, String realName, int amount);
public UserPaymentDto wxCheckOrderStatus(String tradeno);
public UserPaymentDto aliCheckOrderStatus(String tradno);
}
......@@ -11,50 +11,29 @@ import com.edgec.browserbackend.account.service.EmailService;
import com.edgec.browserbackend.account.service.SmsUtils;
import com.edgec.browserbackend.account.utils.AccountServicePool;
import com.edgec.browserbackend.auth.exception.AuthErrorCode;
import com.edgec.browserbackend.auth.repository.UserRepository;
import com.edgec.browserbackend.auth.service.UserAuthService;
import com.edgec.browserbackend.auth.service.UserService;
import com.edgec.browserbackend.browser.ErrorCode.BrowserErrorCode;
import com.edgec.browserbackend.browser.domain.IpSummary;
import com.edgec.browserbackend.browser.domain.ShopSummary;
import com.edgec.browserbackend.browser.dto.PageInfo;
import com.edgec.browserbackend.browser.dto.ShopPageResultDto;
import com.edgec.browserbackend.browser.dto.ShopResultDto;
import com.edgec.browserbackend.browser.service.IpResourceService;
import com.edgec.browserbackend.browser.service.ShopService;
import com.edgec.browserbackend.common.commons.error.ClientRequestException;
import com.edgec.browserbackend.common.commons.utils.CommonStringUtils;
import com.edgec.browserbackend.common.utils.Aes;
import com.edgec.browserbackend.common.utils.FileUtil;
import com.mongodb.DB;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSInputFile;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.StringUtils;
import java.io.*;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.YearMonth;
......@@ -62,12 +41,8 @@ import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static org.springframework.data.mongodb.core.query.Query.query;
import static org.springframework.data.mongodb.gridfs.GridFsCriteria.whereFilename;
@Service
@Transactional
@ComponentScan("com.edgec.browserbackend.account.repository")
......@@ -105,7 +80,7 @@ public class AccountServiceImpl implements AccountService {
private InvoiceRepository invoiceRepository;
@Autowired
private UserAuthService userAuthService;
private UserService userService;
@Autowired
private ShopService shopService;
......@@ -424,7 +399,7 @@ public class AccountServiceImpl implements AccountService {
}
public void deleteByName(String name) {
userAuthService.deleteUser(name);
userService.deleteUser(name);
repository.deleteById(name);
}
......@@ -443,7 +418,7 @@ public class AccountServiceImpl implements AccountService {
throw new ClientRequestException(AccountErrorCode.UNKNOWN, "Invalid Request");
}
userAuthService.deleteUser(child);
userService.deleteUser(child);
repository.delete(childAccount);
Account parentAccount = repository.findByName(parent);
parentAccount.setChildCount(parentAccount.getChildCount() - 1);
......@@ -518,7 +493,7 @@ public class AccountServiceImpl implements AccountService {
user.setEnabled(true);
userAuthService.create(new com.edgec.browserbackend.auth.domain.User(user));
userService.create(new com.edgec.browserbackend.auth.domain.User(user));
repository.save(account);
JSONObject param = new JSONObject();
......@@ -573,7 +548,7 @@ public class AccountServiceImpl implements AccountService {
emailService.sendEmailVerification(user.getUsername(), user.getEmail(), user.getVerificationCode());
userAuthService.create(new com.edgec.browserbackend.auth.domain.User(user));
userService.create(new com.edgec.browserbackend.auth.domain.User(user));
repository.save(account);
log.info("new account has been created: " + account.getName());
......@@ -701,7 +676,7 @@ public class AccountServiceImpl implements AccountService {
authUser.setEmail(user.getEmail());
authUser.setEnabled(true);
authUser.setPermission(user.getPermission());
userAuthService.create(new com.edgec.browserbackend.auth.domain.User(authUser));
userService.create(new com.edgec.browserbackend.auth.domain.User(authUser));
Account account = new Account(user);
List<String> whiteList = new ArrayList<>();
......@@ -775,7 +750,7 @@ public class AccountServiceImpl implements AccountService {
authUser.setPermission(subUsersRequestDto.getPermission());
else
authUser.setPermission(0);
userAuthService.create(new com.edgec.browserbackend.auth.domain.User(authUser));
userService.create(new com.edgec.browserbackend.auth.domain.User(authUser));
Account account = new Account(user);
account.setPhoneNumber(existing.getPhoneNumber());
......@@ -837,7 +812,7 @@ public class AccountServiceImpl implements AccountService {
if (subUsersRequestDto.getPassword() != null) {
user.setPassword(Aes.aesDecrypt(subUsersRequestDto.getPassword()));
}
userAuthService.resetUserPassword(user);
userService.resetUserPassword(user);
}
if (subUsersRequestDto.getNickname() != null)
......@@ -902,7 +877,7 @@ public class AccountServiceImpl implements AccountService {
User newuser = new User();
newuser.setUsername(account.getName());
newuser.setEmail(update.getEmail());
userAuthService.updateUser(name, new com.edgec.browserbackend.auth.domain.User(newuser));
userService.updateUser(name, new com.edgec.browserbackend.auth.domain.User(newuser));
}
repository.save(account);
return account;
......@@ -922,7 +897,7 @@ public class AccountServiceImpl implements AccountService {
newuser.setUsername(account.getName());
String code = UUID.randomUUID().toString() + System.currentTimeMillis();
newuser.setVerificationCode(code);
userAuthService.reset(new com.edgec.browserbackend.auth.domain.User(newuser));
userService.reset(new com.edgec.browserbackend.auth.domain.User(newuser));
emailService.sendResetPassword(account.getName(), account.getEmail(), code);
log.info("password has been reset for: " + user);
......@@ -964,7 +939,7 @@ public class AccountServiceImpl implements AccountService {
client.setUsername(account.getName());
client.setPassword(user.getPassword());
userAuthService.resetUserPassword(new com.edgec.browserbackend.auth.domain.User(client));
userService.resetUserPassword(new com.edgec.browserbackend.auth.domain.User(client));
}
......
......@@ -8,10 +8,9 @@ import com.edgec.browserbackend.account.dto.PromotionQueryResultDto;
import com.edgec.browserbackend.account.exception.AccountErrorCode;
import com.edgec.browserbackend.account.repository.*;
import com.edgec.browserbackend.account.service.AdministratorService;
import com.edgec.browserbackend.auth.service.UserAuthService;
import com.edgec.browserbackend.auth.service.UserService;
import com.edgec.browserbackend.browser.ErrorCode.BrowserErrorCode;
import com.edgec.browserbackend.browser.repository.IpResourceRepository;
import com.edgec.browserbackend.common.charge.ChargeType;
import com.edgec.browserbackend.common.commons.error.ClientRequestException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
......@@ -26,7 +25,6 @@ import org.springframework.stereotype.Service;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.YearMonth;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.*;
......@@ -54,7 +52,7 @@ public class AdministratorServiceImpl implements AdministratorService {
private UserBillingRepository userBillingRepository;
@Autowired
private UserAuthService userAuthService;
private UserService userService;
@Autowired
private IpResourceRepository ipResourceRepository;
......@@ -75,7 +73,7 @@ public class AdministratorServiceImpl implements AdministratorService {
newUser.setPassword(administrator.getPassword());
newUser.setEnabled(true);
userAuthService.create(new com.edgec.browserbackend.auth.domain.User(newUser));
userService.create(new com.edgec.browserbackend.auth.domain.User(newUser));
administrator1.setPassword("");
administratorRepository.save(administrator1);
......@@ -191,7 +189,7 @@ public class AdministratorServiceImpl implements AdministratorService {
User newUser = new User();
newUser.setUsername(name);
userAuthService.unlock(new com.edgec.browserbackend.auth.domain.User(newUser),"unlock");
userService.unlock(new com.edgec.browserbackend.auth.domain.User(newUser),"unlock");
return newAccount;
}
......@@ -206,7 +204,7 @@ public class AdministratorServiceImpl implements AdministratorService {
User abnormalUser = new User();
abnormalUser.setUsername(name);
userAuthService.lock(new com.edgec.browserbackend.auth.domain.User(abnormalUser),"lock");
userService.lock(new com.edgec.browserbackend.auth.domain.User(abnormalUser),"lock");
accountRepository.save(abnormalAccount);
......@@ -249,7 +247,7 @@ public class AdministratorServiceImpl implements AdministratorService {
if (administrator == null) {
throw new ClientRequestException(AccountErrorCode.UNKNOWN, "Invalid Request");
}
userAuthService.deleteUser(name);
userService.deleteUser(name);
administratorRepository.delete(administrator);
}
......@@ -261,7 +259,7 @@ public class AdministratorServiceImpl implements AdministratorService {
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST, "can't find adminstrator with name " + name);
}
updating.setRole(roles);
userAuthService.updateRoles(name, roles);
userService.updateRoles(name, roles);
administratorRepository.save(updating);
return updating;
......@@ -312,13 +310,13 @@ public class AdministratorServiceImpl implements AdministratorService {
@Override
public boolean getUserLockState(String name) {
return userAuthService.lockState(name);
return userService.lockState(name);
}
@Override
public void deleteUser(String username) {
userAuthService.deleteUser(username);
userService.deleteUser(username);
accountRepository.deleteById(username);
}
......
......@@ -685,4 +685,162 @@ public class PaymentServiceImpl implements PaymentService {
}
}
@Override
public UserPaymentDto wxCheckOrderStatus(String tradeno) {
UserPaymentDto result = new UserPaymentDto();
result.setPaid(false);
try {
UserPayment byTradeNo = userPaymentRepository.findByTradeNo(tradeno);
if (PaymentMethod.ALIPAY.equals(byTradeNo.getPaymentMethod()))
return aliCheckOrderStatus(tradeno);
UserBalance balance = userBalanceRepository.findById(byTradeNo.getUsername()).orElse(null);
if (balance != null)
result.setBalance(Math.round(balance.getBalanced()));
if (byTradeNo == null)
return result;
if (byTradeNo.isSucceed()) {
result.setPaid(true);
return result;
}
Account byName = accountService.findByName(byTradeNo.getUsername());
if (byName == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST, "account does not exist: " + byTradeNo.getUsername());
boolean isVpsClient = true;
WXPayConfig ourWxPayConfig = isVpsClient ? new FGLWxConfig() : new CloudamWxConfig();
WXPay wxPay = new WXPay(ourWxPayConfig);
Map<String, String> data = new HashMap<>();
data.put("appid", ourWxPayConfig.getAppID());
data.put("mch_id", ourWxPayConfig.getMchID()); //商户号
data.put("out_trade_no", tradeno); //交易号
data.put("nonce_str", SmsUtils.createRandom(false, 24)); // 随机字符串小于32位
String s = WXPayUtil.generateSignature(data, ourWxPayConfig.getKey()); //签名
data.put("sign", s);
Map<String, String> respData = wxPay.orderQuery(data);
if (respData.get("return_code").equals("SUCCESS") && respData.get("return_msg").equals("OK") && "SUCCESS".equals(respData.get("result_code"))) {
/**
*
SUCCESS—支付成功
REFUND—转入退款
NOTPAY—未支付
CLOSED—已关闭
REVOKED—已撤销(付款码支付)
USERPAYING--用户支付中(付款码支付)
PAYERROR--支付失败(其他原因,如银行返回失败) *
*/
result.setStatus(respData.get("trade_state"));
if ("SUCCESS".equals(respData.get("trade_state"))) {
byTradeNo.setSucceed(true);
boolean b = userPaymentRepository.updatePaymentResult(byTradeNo, true);
if (b) {
if (balance == null) {
balance = new UserBalance();
balance.setUsername(byTradeNo.getUsername());
}
balance.setBalanced(balance.getBalanced() + byTradeNo.getAmount());
userBalanceRepository.save(balance);
}
result.setBalance(Math.round(balance.getBalanced()));
result.setPaid(true);
return result;
}
}
result.setPaid(false);
} catch (Exception e) {
log.error("Wechat payment order generation fails", e);
result.setPaid(false);
}
return result;
}
@Override
public UserPaymentDto aliCheckOrderStatus(String tradno) {
UserPaymentDto result = new UserPaymentDto();
result.setPaid(false);
try {
UserPayment byTradeNo = userPaymentRepository.findByTradeNo(tradno);
UserBalance balance = userBalanceRepository.findById(byTradeNo.getUsername()).orElse(null);
if (balance != null)
result.setBalance(Math.round(balance.getBalanced()));
if (byTradeNo == null)
return result;
if (byTradeNo.isSucceed()) {
result.setPaid(true);
return result;
}
Account byName = accountService.findByName(byTradeNo.getUsername());
if (byName == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST, "account does not exist: " + byTradeNo.getUsername());
boolean isVpsClient = true;
AlipayConfig alipayConfig = isVpsClient ? new VpsAlipayConfig() : new CloudamAlipayConfig();
AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getURL(), alipayConfig.getAPPID(), alipayConfig.getAPP_PRIVATE_KEY(),
"json", alipayConfig.getCHARSET(), alipayConfig.getALIPAY_PUBLIC_KEY(), alipayConfig.getSIGN_TYPE());
AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
String out_trade_no = byTradeNo.getTradeNo();
alipayRequest.setBizContent(""
+ "{"
+ "\"out_trade_no\":\"" + out_trade_no + "\""
+ "}"
);
AlipayTradeQueryResponse response = alipayClient.execute(alipayRequest);
log.error("ali order status :" + JSONObject.toJSONString(response));
result.setStatus(convertAlipayStatus(response.getTradeStatus()));
if ("TRADE_SUCCESS".equals(response.getTradeStatus()) || "TRADE_FINISHED".equals(response.getTradeStatus())) {
byTradeNo.setSucceed(true);
boolean b = userPaymentRepository.updatePaymentResult(byTradeNo, true);
if (b) {
if (balance == null) {
balance = new UserBalance();
balance.setUsername(byTradeNo.getUsername());
}
balance.setBalanced(balance.getBalanced() + byTradeNo.getAmount());
userBalanceRepository.save(balance);
}
result.setBalance(Math.round(balance.getBalanced()));
result.setPaid(true);
return result;
}
result.setPaid(false);
} catch (Exception e) {
log.error("Alipay payment order generation fails", e);
result.setPaid(false);
}
return result;
}
}
......@@ -17,6 +17,7 @@ import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import java.util.*;
......
package com.edgec.browserbackend.auth.config;
import com.edgec.browserbackend.auth.service.MongoTokenStore;
import com.edgec.browserbackend.auth.service.security.MongoUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
......@@ -24,7 +25,10 @@ import org.springframework.security.oauth2.provider.token.store.InMemoryTokenSto
public class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {
private final String NOOP_PASSWORD_ENCODE = "{noop}";
private TokenStore tokenStore = new InMemoryTokenStore();
@Autowired
private MongoTokenStore mongoTokenStore;
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
......@@ -48,6 +52,8 @@ public class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdap
.withClient("browser")
.authorizedGrantTypes("refresh_token", "password")
.scopes("browser")
.accessTokenValiditySeconds(43200)
.refreshTokenValiditySeconds(43200)
.and()
.withClient("cloudam-browser")
.secret(env.getProperty("ACCOUNT_SERVICE_PASSWORD"))
......@@ -59,7 +65,7 @@ public class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdap
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.tokenStore(tokenStore)
.tokenStore(mongoTokenStore)
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService).exceptionTranslator(oAuthResponseExceptionTranslator);
}
......
package com.edgec.browserbackend.auth.controller;
import com.edgec.browserbackend.auth.domain.UsernameToken;
import com.edgec.browserbackend.auth.service.UsernameTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal;
import java.util.List;
@RestController
public class TokenController {
@Autowired
private UsernameTokenService usernameTokenService;
@RequestMapping(path = "/token", method = RequestMethod.GET)
public List<UsernameToken> selectVpsDtoByParent(Principal principal) {
return usernameTokenService.selectVpsDtoByParent(principal.getName());
}
@RequestMapping(path = "/token", method = RequestMethod.POST)
public UsernameToken createToken(Principal principal, @RequestParam(value = "username") String username) {
return usernameTokenService.createUserToken(principal.getName(), username);
}
}
......@@ -3,11 +3,9 @@ package com.edgec.browserbackend.auth.controller;
import com.edgec.browserbackend.account.dto.ResultDto;
import com.edgec.browserbackend.auth.domain.User;
import com.edgec.browserbackend.auth.domain.UserPasswordReset;
import com.edgec.browserbackend.auth.service.UserAuthService;
import com.edgec.browserbackend.auth.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.token.TokenService;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.*;
......@@ -22,7 +20,7 @@ import java.util.Map;
public class UserController {
@Autowired
private UserAuthService userAuthService;
private UserService userService;
@Autowired
ConsumerTokenServices consumerTokenServices;
......@@ -44,41 +42,41 @@ public class UserController {
@RequestMapping(path = "/{name}/roles/{roles}", method = RequestMethod.PUT)
public void updateRoles(@PathVariable String name, @PathVariable String roles) {
userAuthService.updateRoles(name, roles);
userService.updateRoles(name, roles);
}
@RequestMapping(path = "/{name}/addroles/{roles}", method = RequestMethod.PUT)
public void addRoles(@PathVariable String name, @PathVariable String roles) {
userAuthService.addRoles(name, roles);
userService.addRoles(name, roles);
}
@RequestMapping(method = RequestMethod.POST)
public void createUser(@Valid @RequestBody User user) {
userAuthService.create(user);
userService.create(user);
}
@RequestMapping(value = "/resetpasswd", method = RequestMethod.POST)
public void resetUserPassword(@Valid @RequestBody User user) {
userAuthService.resetUserPassword(user);
userService.resetUserPassword(user);
}
@RequestMapping(path = "/current/{name}", method = RequestMethod.DELETE)
public void deleteUser(@PathVariable String name) {
userAuthService.deleteUser(name);
userService.deleteUser(name);
}
@RequestMapping(method = RequestMethod.PUT)
public void resetUser(@Valid @RequestBody User user) {
userAuthService.reset(user);
userService.reset(user);
}
@RequestMapping(path = "/{lockOrUnlock}",method = RequestMethod.PUT)
public void lockOrUnlockUser(@Valid @RequestBody User user, @PathVariable String lockOrUnlock) {//@RequestParam("by") String by,
if("lock".equals(lockOrUnlock)){
userAuthService.lock(user,lockOrUnlock);
userService.lock(user,lockOrUnlock);
}
else if("unlock".equals(lockOrUnlock)){
userAuthService.unlock(user,lockOrUnlock);
userService.unlock(user,lockOrUnlock);
}
}
......@@ -89,19 +87,19 @@ public class UserController {
@RequestMapping(path = "/{name}", method = RequestMethod.GET)
public boolean lockState(@PathVariable String name) {
return userAuthService.lockState(name);
return userService.lockState(name);
}
@RequestMapping(path = "/verify/{name}/{code}", method = RequestMethod.PUT)
public void verifyCode(@PathVariable String name, @PathVariable String code) {
userAuthService.verifyCode(name, code);
userService.verifyCode(name, code);
}
@RequestMapping(path = "/changepass", method = RequestMethod.PUT)
public ResultDto changePassword(@Valid @RequestBody UserPasswordReset userPasswordReset) {
ResultDto resultDto = new ResultDto();
try {
resultDto.setData(userAuthService.changePassword(userPasswordReset));
resultDto.setData(userService.changePassword(userPasswordReset));
resultDto.setStatus(0);
} catch (Exception e) {
resultDto.setStatus(-1);
......@@ -116,7 +114,7 @@ public class UserController {
@PreAuthorize("#oauth2.hasScope('server')")
@RequestMapping(path = "/updateuser",method = RequestMethod.PUT)
public void updateUser(@Valid @RequestBody User user, @RequestParam String username) {//@RequestParam("by") String by,
userAuthService.updateUser(username, user);
userService.updateUser(username, user);
}
......
package com.edgec.browserbackend.auth.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "usernametoken")
@JsonIgnoreProperties(ignoreUnknown = true)
public class UsernameToken {
@Id
private String username;
private String token;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
package com.edgec.browserbackend.auth.domain.mongo;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.data.mongodb.core.mapping.Document;
import java.time.Instant;
import java.util.Arrays;
import java.util.Objects;
@Document
public class MongoOAuth2AccessToken {
@Id
private String tokenId;
private byte[] token;
private String authenticationId;
private String username;
private String clientId;
private byte[] authentication;
private String refreshToken;
private long createdAt;
public MongoOAuth2AccessToken() {
}
@PersistenceConstructor
public MongoOAuth2AccessToken(final String tokenId,
final byte[] token,
final String authenticationId,
final String username,
final String clientId,
final byte[] authentication,
final String refreshToken) {
this.tokenId = tokenId;
this.token = token;
this.authenticationId = authenticationId;
this.username = username;
this.clientId = clientId;
this.authentication = authentication;
this.refreshToken = refreshToken;
this.createdAt = Instant.now().toEpochMilli();
}
public String getTokenId() {
return tokenId;
}
public byte[] getToken() {
return token;
}
public String getAuthenticationId() {
return authenticationId;
}
public String getUsername() {
return username;
}
public String getClientId() {
return clientId;
}
public byte[] getAuthentication() {
return authentication;
}
public String getRefreshToken() {
return refreshToken;
}
@Override
public int hashCode() {
return Objects.hash(token, authenticationId, username, clientId, authentication, refreshToken);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final MongoOAuth2AccessToken other = (MongoOAuth2AccessToken) obj;
return Objects.equals(this.token, other.token) && Objects.equals(this.authenticationId, other.authenticationId) && Objects.equals(this.username, other.username) && Objects.equals(this.clientId, other.clientId) && Objects.equals(this.authentication, other.authentication) && Objects.equals(this.refreshToken, other.refreshToken);
}
@Override
public String toString() {
return "MongoOAuth2AccessToken{" +
"tokenId='" + tokenId + '\'' +
", token=" + Arrays.toString(token) +
", authenticationId='" + authenticationId + '\'' +
", username='" + username + '\'' +
", clientId='" + clientId + '\'' +
", authentication=" + Arrays.toString(authentication) +
", refreshToken='" + refreshToken + '\'' +
'}';
}
public long getCreatedAt() {
return createdAt;
}
public void setCreatedAt(long createdAt) {
this.createdAt = createdAt;
}
}
package com.edgec.browserbackend.auth.domain.mongo;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.data.mongodb.core.mapping.Document;
import java.time.Instant;
@Document
public class MongoOAuth2RefreshToken {
@Id
private String tokenId;
private byte[] token;
private byte[] authentication;
private long createdAt;
public MongoOAuth2RefreshToken() {
}
@PersistenceConstructor
public MongoOAuth2RefreshToken(final String tokenId,
final byte[] token,
final byte[] authentication) {
this.tokenId = tokenId;
this.token = token;
this.authentication = authentication;
this.createdAt = Instant.now().toEpochMilli();
}
public String getTokenId() {
return tokenId;
}
public byte[] getToken() {
return token;
}
public byte[] getAuthentication() {
return authentication;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof MongoOAuth2RefreshToken)) return false;
MongoOAuth2RefreshToken that = (MongoOAuth2RefreshToken) o;
return new EqualsBuilder()
.append(tokenId, that.tokenId)
.append(token, that.token)
.append(authentication, that.authentication)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37)
.append(tokenId)
.append(token)
.append(authentication)
.toHashCode();
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("tokenId", tokenId)
.append("token", token)
.append("authentication", authentication)
.toString();
}
public long getCreatedAt() {
return createdAt;
}
public void setCreatedAt(long createdAt) {
this.createdAt = createdAt;
}
}
package com.edgec.browserbackend.auth.repository;
import com.edgec.browserbackend.auth.domain.UsernameToken;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UsernameTokenRepository extends MongoRepository<UsernameToken,String> {
UsernameToken findByUsername(String username);
}
package com.edgec.browserbackend.auth.repository.mongo;
import com.edgec.browserbackend.auth.domain.mongo.MongoOAuth2AccessToken;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
public interface MongoOAuth2AccessTokenRepository extends MongoRepository<MongoOAuth2AccessToken, String>, MongoOAuth2AccessTokenRepositoryBase {
List<MongoOAuth2AccessToken> findByCreatedAtGreaterThan(long validtime);
}
package com.edgec.browserbackend.auth.repository.mongo;
import com.edgec.browserbackend.auth.domain.mongo.MongoOAuth2AccessToken;
import java.util.List;
public interface MongoOAuth2AccessTokenRepositoryBase {
MongoOAuth2AccessToken findByTokenId(String tokenId);
boolean deleteByTokenId(String tokenId);
boolean deleteByRefreshTokenId(String refreshTokenId);
MongoOAuth2AccessToken findByAuthenticationId(String key);
List<MongoOAuth2AccessToken> findByUsernameAndClientId(String username, String clientId);
List<MongoOAuth2AccessToken> findByClientId(String clientId);
}
package com.edgec.browserbackend.auth.repository.mongo;
import com.edgec.browserbackend.auth.domain.mongo.MongoOAuth2AccessToken;
import com.mongodb.client.result.DeleteResult;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class MongoOAuth2AccessTokenRepositoryImpl implements MongoOAuth2AccessTokenRepositoryBase {
public static final String ID = "_id";
private final MongoTemplate mongoTemplate;
public MongoOAuth2AccessTokenRepositoryImpl(final MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
@Override
public MongoOAuth2AccessToken findByTokenId(final String tokenId) {
final Query query = Query.query(Criteria.where(ID).is(tokenId));
return mongoTemplate.findOne(query, MongoOAuth2AccessToken.class);
}
@Override
public boolean deleteByTokenId(final String tokenId) {
final Query query = Query.query(Criteria.where(ID).is(tokenId));
final DeleteResult deleteResult = mongoTemplate.remove(query, MongoOAuth2AccessToken.class);
return deleteResult.wasAcknowledged();
}
@Override
public boolean deleteByRefreshTokenId(String refreshTokenId) {
final Query query = Query.query(Criteria.where("refreshToken").is(refreshTokenId));
final DeleteResult deleteResult = mongoTemplate.remove(query, MongoOAuth2AccessToken.class);
return deleteResult.wasAcknowledged();
}
@Override
public MongoOAuth2AccessToken findByAuthenticationId(String key) {
final Query query = Query.query(Criteria.where("authenticationId").is(key));
return mongoTemplate.findOne(query, MongoOAuth2AccessToken.class);
}
@Override
public List<MongoOAuth2AccessToken> findByUsernameAndClientId(final String username,
final String clientId) {
final Query query = Query.query(Criteria.where("username").is(username).andOperator(Criteria.where("clientId").is(clientId)));
return mongoTemplate.find(query, MongoOAuth2AccessToken.class);
}
@Override
public List<MongoOAuth2AccessToken> findByClientId(final String clientId) {
final Query query = Query.query(Criteria.where("clientId").is(clientId));
return mongoTemplate.find(query, MongoOAuth2AccessToken.class);
}
}
package com.edgec.browserbackend.auth.repository.mongo;
import com.edgec.browserbackend.auth.domain.mongo.MongoOAuth2RefreshToken;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface MongoOAuth2RefreshTokenRepository extends MongoRepository<MongoOAuth2RefreshToken, String>, MongoOAuth2RefreshTokenRepositoryBase {
}
package com.edgec.browserbackend.auth.repository.mongo;
import com.edgec.browserbackend.auth.domain.mongo.MongoOAuth2RefreshToken;
public interface MongoOAuth2RefreshTokenRepositoryBase {
MongoOAuth2RefreshToken findByTokenId(String tokenId);
boolean deleteByTokenId(String tokenId);
}
package com.edgec.browserbackend.auth.repository.mongo;
import com.edgec.browserbackend.auth.domain.mongo.MongoOAuth2RefreshToken;
import com.mongodb.client.result.DeleteResult;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;
@Component
public class MongoOAuth2RefreshTokenRepositoryImpl implements MongoOAuth2RefreshTokenRepositoryBase {
public static final String ID = "_id";
private MongoTemplate mongoTemplate;
public MongoOAuth2RefreshTokenRepositoryImpl(final MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
@Override
public MongoOAuth2RefreshToken findByTokenId(final String tokenId) {
final Query query = Query.query(Criteria.where(ID).is(tokenId));
return mongoTemplate.findOne(query, MongoOAuth2RefreshToken.class);
}
@Override
public boolean deleteByTokenId(final String tokenId) {
final Query query = Query.query(Criteria.where(ID).is(tokenId));
final DeleteResult deleteResult = mongoTemplate.remove(query, MongoOAuth2RefreshToken.class);
return deleteResult.wasAcknowledged();
}
}
......@@ -6,7 +6,7 @@ import com.edgec.browserbackend.auth.domain.UserPasswordReset;
import com.edgec.browserbackend.auth.exception.AuthErrorCode;
import com.edgec.browserbackend.auth.repository.RolesRepository;
import com.edgec.browserbackend.auth.repository.UserRepository;
import com.edgec.browserbackend.auth.service.UserAuthService;
import com.edgec.browserbackend.auth.service.UserService;
import com.edgec.browserbackend.common.commons.error.ClientRequestException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
......@@ -18,7 +18,7 @@ import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class UserAuthServiceImpl implements UserAuthService {
public class UserServiceImpl implements UserService {
private static final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
private final Logger log = LoggerFactory.getLogger(getClass());
......
package com.edgec.browserbackend.auth.service.Impl;
import com.edgec.browserbackend.account.domain.Account;
import com.edgec.browserbackend.account.domain.AccountDto;
import com.edgec.browserbackend.account.domain.UserDto;
import com.edgec.browserbackend.account.service.AccountService;
import com.edgec.browserbackend.auth.domain.UsernameToken;
import com.edgec.browserbackend.auth.exception.AuthErrorCode;
import com.edgec.browserbackend.auth.repository.UsernameTokenRepository;
import com.edgec.browserbackend.auth.service.UsernameTokenService;
import com.edgec.browserbackend.common.commons.error.ClientRequestException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;
@Service
public class UsernameTokenServiceImpl implements UsernameTokenService {
@Autowired
private UsernameTokenRepository usernameTokenRepository;
@Autowired
private AccountService accountSecrvice;
@Override
public List<UsernameToken> selectVpsDtoByParent(String username) {
List<UserDto> userDtos = accountSecrvice.getAllDesendentUsers(username, 0);
List<UsernameToken> usernameTokens = userDtos.stream().map(userDto -> {
return usernameTokenRepository.findByUsername(userDto.getUsername());
}).filter(Objects::nonNull).collect(Collectors.toList());
UsernameToken parentToken = usernameTokenRepository.findByUsername(username);
if (parentToken != null) {
usernameTokens.add(parentToken);
}
return usernameTokens;
}
public UsernameToken createUsername(String username) {
String token = UUID.randomUUID().toString();
UsernameToken usernameToken = new UsernameToken();
usernameToken.setToken(token);
usernameToken.setUsername(username);
usernameTokenRepository.save(usernameToken);
return usernameToken;
}
@Override
public UsernameToken getUserToken(String username) {
return usernameTokenRepository.findByUsername(username);
}
public UsernameToken createUserToken(String owner, String targetUser) {
Account account = accountSecrvice.findByName(targetUser);
if (owner.equals(account.getParent()) || owner.equals(targetUser)) {
String token = UUID.randomUUID().toString().replace("-","");
UsernameToken usernameToken = new UsernameToken();
usernameToken.setToken(token);
usernameToken.setUsername(targetUser);
usernameTokenRepository.save(usernameToken);
return usernameToken;
}
throw new ClientRequestException(AuthErrorCode.AUTHORIZATION_ERROR);
}
}
package com.edgec.browserbackend.auth.service;
import com.edgec.browserbackend.auth.domain.mongo.MongoOAuth2AccessToken;
import com.edgec.browserbackend.auth.domain.mongo.MongoOAuth2RefreshToken;
import com.edgec.browserbackend.auth.repository.mongo.MongoOAuth2AccessTokenRepository;
import com.edgec.browserbackend.auth.repository.mongo.MongoOAuth2RefreshTokenRepository;
import org.springframework.context.annotation.Bean;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.common.util.SerializationUtils;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.AuthenticationKeyGenerator;
import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Component;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import static java.util.Objects.nonNull;
import static org.springframework.security.oauth2.common.util.SerializationUtils.deserialize;
import static org.springframework.security.oauth2.common.util.SerializationUtils.serialize;
@Component
public class MongoTokenStore implements TokenStore {
private final MongoOAuth2AccessTokenRepository mongoOAuth2AccessTokenRepository;
private final MongoOAuth2RefreshTokenRepository mongoOAuth2RefreshTokenRepository;
private final AuthenticationKeyGenerator authenticationKeyGenerator;
public MongoTokenStore(final MongoOAuth2AccessTokenRepository mongoOAuth2AccessTokenRepository,
final MongoOAuth2RefreshTokenRepository mongoOAuth2RefreshTokenRepository,
final AuthenticationKeyGenerator authenticationKeyGenerator) {
this.mongoOAuth2AccessTokenRepository = mongoOAuth2AccessTokenRepository;
this.mongoOAuth2RefreshTokenRepository = mongoOAuth2RefreshTokenRepository;
this.authenticationKeyGenerator = authenticationKeyGenerator;
}
@Override
public OAuth2Authentication readAuthentication(final OAuth2AccessToken token) {
return readAuthentication(token.getValue());
}
@Override
public OAuth2Authentication readAuthentication(final String token) {
final String tokenId = extractTokenKey(token);
final MongoOAuth2AccessToken mongoOAuth2AccessToken = mongoOAuth2AccessTokenRepository.findByTokenId(tokenId);
if (nonNull(mongoOAuth2AccessToken)) {
try {
return deserializeAuthentication(mongoOAuth2AccessToken.getAuthentication());
} catch (IllegalArgumentException e) {
removeAccessToken(token);
}
}
return null;
}
@Override
public void storeAccessToken(final OAuth2AccessToken token,
final OAuth2Authentication authentication) {
String refreshToken = null;
if (nonNull(token.getRefreshToken())) {
refreshToken = token.getRefreshToken().getValue();
}
if (nonNull(readAccessToken(token.getValue()))) {
removeAccessToken(token.getValue());
}
final String tokenKey = extractTokenKey(token.getValue());
final MongoOAuth2AccessToken oAuth2AccessToken = new MongoOAuth2AccessToken(tokenKey,
serializeAccessToken(token),
authenticationKeyGenerator.extractKey(authentication),
authentication.isClientOnly() ? null : authentication.getName(),
authentication.getOAuth2Request().getClientId(),
serializeAuthentication(authentication),
extractTokenKey(refreshToken));
mongoOAuth2AccessTokenRepository.save(oAuth2AccessToken);
}
@Override
public OAuth2AccessToken readAccessToken(final String tokenValue) {
final String tokenKey = extractTokenKey(tokenValue);
final MongoOAuth2AccessToken mongoOAuth2AccessToken = mongoOAuth2AccessTokenRepository.findByTokenId(tokenKey);
if (nonNull(mongoOAuth2AccessToken)) {
try {
return deserializeAccessToken(mongoOAuth2AccessToken.getToken());
} catch (IllegalArgumentException e) {
removeAccessToken(tokenValue);
}
}
return null;
}
@Override
public void removeAccessToken(final OAuth2AccessToken token) {
removeAccessToken(token.getValue());
}
@Override
public void storeRefreshToken(final OAuth2RefreshToken refreshToken,
final OAuth2Authentication oAuth2Authentication) {
final String tokenKey = extractTokenKey(refreshToken.getValue());
final byte[] token = serializeRefreshToken(refreshToken);
final byte[] authentication = serializeAuthentication(oAuth2Authentication);
final MongoOAuth2RefreshToken oAuth2RefreshToken = new MongoOAuth2RefreshToken(tokenKey, token, authentication);
mongoOAuth2RefreshTokenRepository.save(oAuth2RefreshToken);
}
@Override
public OAuth2RefreshToken readRefreshToken(final String tokenValue) {
final String tokenKey = extractTokenKey(tokenValue);
final MongoOAuth2RefreshToken mongoOAuth2RefreshToken = mongoOAuth2RefreshTokenRepository.findByTokenId(tokenKey);
if (nonNull(mongoOAuth2RefreshToken)) {
try {
return deserializeRefreshToken(mongoOAuth2RefreshToken.getToken());
} catch (IllegalArgumentException e) {
removeRefreshToken(tokenValue);
}
}
return null;
}
@Override
public OAuth2Authentication readAuthenticationForRefreshToken(final OAuth2RefreshToken token) {
return readAuthenticationForRefreshToken(token.getValue());
}
@Override
public void removeRefreshToken(final OAuth2RefreshToken token) {
removeRefreshToken(token.getValue());
}
@Override
public void removeAccessTokenUsingRefreshToken(final OAuth2RefreshToken refreshToken) {
removeAccessTokenUsingRefreshToken(refreshToken.getValue());
}
@Override
public OAuth2AccessToken getAccessToken(final OAuth2Authentication authentication) {
OAuth2AccessToken accessToken = null;
String key = authenticationKeyGenerator.extractKey(authentication);
final MongoOAuth2AccessToken oAuth2AccessToken = mongoOAuth2AccessTokenRepository.findByAuthenticationId(key);
if (oAuth2AccessToken != null) {
accessToken = deserializeAccessToken(oAuth2AccessToken.getToken());
}
if (accessToken != null
&& !key.equals(authenticationKeyGenerator.extractKey(readAuthentication(accessToken.getValue())))) {
removeAccessToken(accessToken.getValue());
// Keep the store consistent (maybe the same user is represented by this authentication but the details have
// changed)
storeAccessToken(accessToken, authentication);
}
return accessToken;
}
@Override
public Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName) {
final List<MongoOAuth2AccessToken> oAuth2AccessTokens = mongoOAuth2AccessTokenRepository.findByUsernameAndClientId(userName, clientId);
return transformToOAuth2AccessTokens(oAuth2AccessTokens);
}
@Override
public Collection<OAuth2AccessToken> findTokensByClientId(final String clientId) {
final List<MongoOAuth2AccessToken> oAuth2AccessTokens = mongoOAuth2AccessTokenRepository.findByClientId(clientId);
return transformToOAuth2AccessTokens(oAuth2AccessTokens);
}
protected String extractTokenKey(final String value) {
if (Objects.isNull(value)) {
return null;
}
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
}
catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("MD5 algorithm not available. Fatal (should be in the JDK).");
}
try {
byte[] bytes = digest.digest(value.getBytes("UTF-8"));
return String.format("%032x", new BigInteger(1, bytes));
}
catch (UnsupportedEncodingException e) {
throw new IllegalStateException("UTF-8 encoding not available. Fatal (should be in the JDK).");
}
}
protected byte[] serializeAccessToken(final OAuth2AccessToken token) {
return serialize(token);
}
protected byte[] serializeRefreshToken(final OAuth2RefreshToken token) {
return serialize(token);
}
protected byte[] serializeAuthentication(final OAuth2Authentication authentication) {
return serialize(authentication);
}
protected OAuth2AccessToken deserializeAccessToken(final byte[] token) {
return deserialize(token);
}
protected OAuth2RefreshToken deserializeRefreshToken(final byte[] token) {
return deserialize(token);
}
protected OAuth2Authentication deserializeAuthentication(final byte[] authentication) {
return deserialize(authentication);
}
public OAuth2Authentication readAuthenticationForRefreshToken(final String value) {
final String tokenId = extractTokenKey(value);
final MongoOAuth2RefreshToken mongoOAuth2RefreshToken = mongoOAuth2RefreshTokenRepository.findByTokenId(tokenId);
if (nonNull(mongoOAuth2RefreshToken)) {
try {
return deserializeAuthentication(mongoOAuth2RefreshToken.getAuthentication());
} catch (IllegalArgumentException e) {
removeRefreshToken(value);
}
}
return null;
}
private void removeRefreshToken(final String token) {
final String tokenId = extractTokenKey(token);
mongoOAuth2RefreshTokenRepository.deleteByTokenId(tokenId);
}
private void removeAccessTokenUsingRefreshToken(final String refreshToken) {
final String tokenId = extractTokenKey(refreshToken);
mongoOAuth2AccessTokenRepository.deleteByRefreshTokenId(tokenId);
}
private void removeAccessToken(final String tokenValue) {
final String tokenKey = extractTokenKey(tokenValue);
mongoOAuth2AccessTokenRepository.deleteByTokenId(tokenKey);
}
private Collection<OAuth2AccessToken> transformToOAuth2AccessTokens(final List<MongoOAuth2AccessToken> oAuth2AccessTokens) {
return oAuth2AccessTokens.stream()
.filter(Objects::nonNull)
.map(token -> SerializationUtils.<OAuth2AccessToken>deserialize(token.getToken()))
.collect(Collectors.toList());
}
}
......@@ -4,7 +4,7 @@ package com.edgec.browserbackend.auth.service;
import com.edgec.browserbackend.auth.domain.User;
import com.edgec.browserbackend.auth.domain.UserPasswordReset;
public interface UserAuthService {
public interface UserService {
void create(User user);
......
package com.edgec.browserbackend.auth.service;
import com.edgec.browserbackend.auth.domain.UsernameToken;
import java.util.List;
public interface UsernameTokenService {
List<UsernameToken> selectVpsDtoByParent(String username);
UsernameToken createUserToken(String owner, String targetUser);
UsernameToken getUserToken(String username);
}
......@@ -11,12 +11,11 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.*;
@Service
public class MongoUserDetailsService implements UserDetailsService {
......@@ -27,6 +26,8 @@ public class MongoUserDetailsService implements UserDetailsService {
@Autowired
private RolesRepository rolesRepository;
private final List<String> TEMPORARY_ACCESS_USERNAME_SUFFIX = Arrays.asList("@intellicost");
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
......@@ -40,6 +41,15 @@ public class MongoUserDetailsService implements UserDetailsService {
user = repository.findByPhone(username).orElse(null);
}
if (user == null) {
try {
user = genTemporaryAccessUser(username);
} catch (Exception e) {
e.printStackTrace();
user = null;
}
}
if (user == null)
throw new UsernameNotFoundException(username);
......@@ -59,4 +69,24 @@ public class MongoUserDetailsService implements UserDetailsService {
return user;
}
/**
* For angelia and intellicost temporary access
*
* @param username uuid@intellicost
* @return
*/
private User genTemporaryAccessUser(String username) {
if (StringUtils.isBlank(username) || TEMPORARY_ACCESS_USERNAME_SUFFIX.stream().noneMatch(username::contains)) {
return null;
}
User temporaryUser = new User();
temporaryUser.setUsername(username);
temporaryUser.setEmail(username);
temporaryUser.setEnabled(true);
String pwd = username.split("@")[0];
temporaryUser.setPassword(new BCryptPasswordEncoder().encode(Base64.getEncoder().encodeToString(pwd.getBytes())));
return temporaryUser;
}
}
......@@ -308,7 +308,7 @@ public class ShopServiceImpl implements ShopService {
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
}
UserShop userShop = userShopRepository.findByUsernameAndShopId(username, shopId);
if (account.getPermission() < 8 || userShop == null) {
if (userShop == null) {
throw new ClientRequestException(AccountErrorCode.NOPERMISSION);
}
Shop shop = shopRepository.findById(shopId).orElse(null);
......
package com.edgec.browserbackend.browser.task;
import com.edgec.browserbackend.account.domain.PaymentMethod;
import com.edgec.browserbackend.account.domain.UserPayment;
import com.edgec.browserbackend.account.repository.UserPaymentRepository;
import com.edgec.browserbackend.account.service.PaymentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.List;
@Component
public class PaymentTask {
private static final Logger log = LoggerFactory.getLogger(PaymentTask.class);
@Autowired
private UserPaymentRepository userPaymentRepository;
@Autowired
private PaymentService paymentService;
@Scheduled(fixedDelay = 60000)
public void checkPayments() {
long now = new Date().getTime();
Date date_5min = new Date(now - 5 * 60 * 1000);
Date date_10min = new Date(now - 10 * 60 * 1000);
List<UserPayment> unfinishedPayments = userPaymentRepository.findAllByPaymentDateBetweenAndSucceed(
ZonedDateTime.ofInstant(date_10min.toInstant(), ZoneId.systemDefault())
, ZonedDateTime.ofInstant(date_5min.toInstant(), ZoneId.systemDefault()), false);
if (unfinishedPayments != null && unfinishedPayments.size() > 0) {
unfinishedPayments.stream().forEach(payment -> {
PaymentMethod paymentMethod = payment.getPaymentMethod();
try {
if (PaymentMethod.WECHAT.equals(paymentMethod)) {
paymentService.wxCheckOrderStatus(payment.getTradeNo());
} else if (PaymentMethod.ALIPAY.equals(paymentMethod)) {
paymentService.aliCheckOrderStatus(payment.getTradeNo());
}
} catch (Exception e) {
log.error("checkPayments", e);
}
});
}
}
}
package com.edgec.browserbackend.common.commons.utils;
import ch.ethz.ssh2.*;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class RemoteShellExecutor {
private Logger logger = LoggerFactory.getLogger(RemoteShellExecutor.class);
private Connection conn;
/** 远程机器IP */
private String ip;
/** 用户名 */
private String osUsername;
/** 密码 */
private String password;
private String charset = Charset.defaultCharset().toString();
private static final int TIME_OUT = 1000 * 5 * 60;
public RemoteShellExecutor(String ip, String usr, String pasword) {
this.ip = ip;
this.osUsername = usr;
this.password = pasword;
}
/**
* 登录
* @return
* @throws IOException
*/
public Boolean login() {
boolean flg = false;
try {
conn = new Connection(ip);
conn.connect();// 连接
//判断身份是否已经认证
if (!conn.isAuthenticationComplete()) {
//加锁,防止多线程调用时线程间判断不一致,导致出现重复认证
synchronized (this) {
if (!conn.isAuthenticationComplete()) {
//进行身份认证
flg = conn.authenticateWithPassword(osUsername, password);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
return flg;
}
public void executeCommand(String command, Session session)
throws Exception {
String outStr = "";
String outErr = "";
if (command.equals("")) {
logger.info("执行空指令");
}
PrintWriter out = null;
try {
out = new PrintWriter(new OutputStreamWriter(session.getStdin(),
"UTF-8"));
out.println(command);
out.flush();
} finally {
if (null != out) {
out.close();
}
}
}
/**
* 执行脚本
*
* @param cmds
* @return
* @throws Exception
*/
public int exec(String cmds) throws Exception {
InputStream stdOut = null;
InputStream stdErr = null;
String outStr = "";
String outErr = "";
int ret = -1;
try {
if (login()) {
// Open a new {@link Session} on this connection
Session session = conn.openSession();
// Execute a command on the remote machine.
session.execCommand(cmds);
stdOut = new StreamGobbler(session.getStdout());
outStr = processStream(stdOut, charset);
stdErr = new StreamGobbler(session.getStderr());
outErr = processStream(stdErr, charset);
session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);
System.out.println("outStr=" + outStr);
System.out.println("outErr=" + outErr);
ret = session.getExitStatus();
} else {
throw new Exception("登录远程机器失败" + ip); // 自定义异常类 实现略
}
} finally {
if (conn != null) {
conn.close();
}
IOUtils.closeQuietly(stdOut);
IOUtils.closeQuietly(stdErr);
}
return ret;
}
private String processStream(InputStream in, String charset) throws Exception {
byte[] buf = new byte[1024];
StringBuilder sb = new StringBuilder();
while (in.read(buf) != -1) {
sb.append(new String(buf, charset));
}
return sb.toString();
}
private String processStdErr(InputStream in, String charset)
throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(in, charset));
StringBuffer sb = new StringBuffer();
if (in.available() != 0) {
while (true) {
String line = br.readLine();
if (line == null)
break;
sb.append(line).append(System.getProperty("line.separator"));
}
}
return sb.toString();
}
/**
* 执行脚本
*
* @param cmds
* @return
* @throws Exception
*/
public int execCommand(String cmds) throws Exception {
InputStream stdOut = null;
InputStream stdErr = null;
String outStr = "";
String outErr = "";
int ret = -1;
try {
if (login()) {
Session session = conn.openSession();
// 建立虚拟终端
session.requestPTY("bash");
// 打开一个Shell
session.startShell();
stdOut = new StreamGobbler(session.getStdout());
stdErr = new StreamGobbler(session.getStderr());
BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdOut));
BufferedReader stderrReader = new BufferedReader(new InputStreamReader(stdErr));
// 准备输入命令
PrintWriter out = new PrintWriter(session.getStdin());
// 输入待执行命令
out.println(cmds);
out.println("exit");
// 6. 关闭输入流
out.close();
// 7. 等待,除非1.连接关闭;2.输出数据传送完毕;3.进程状态为退出;4.超时
session.waitForCondition(ChannelCondition.CLOSED | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS , 30000);
logger.error("Here is the output from stdout:");
while (true)
{
String line = stdoutReader.readLine();
if (line == null)
break;
System.out.println(line);
}
logger.error("Here is the output from stderr:");
while (true)
{
String line = stderrReader.readLine();
if (line == null)
break;
System.out.println(line);
}
/* Show exit status, if available (otherwise "null") */
logger.error("ExitCode: " + session.getExitStatus());
ret = session.getExitStatus();
session.close();/* Close this session */
conn.close();/* Close the connection */
} else {
throw new Exception("登录远程机器失败" + ip); // 自定义异常类 实现略
}
} finally {
if (conn != null) {
conn.close();
}
IOUtils.closeQuietly(stdOut);
IOUtils.closeQuietly(stdErr);
}
return ret;
}
/**
* 远程传输单个文件
*
* @param localFile
* @param remoteTargetDirectory
* @throws IOException
*/
public void transferFile(String localFile, String remoteTargetDirectory) throws Exception {
File file = new File(localFile);
if (file.isDirectory()) {
throw new RuntimeException(localFile + " is not a file");
}
String fileName = file.getName();
System.out.println(fileName);
try {
Session session = conn.openSession();
executeCommand("mkdir -p " + remoteTargetDirectory, session);
} catch (Exception e) {
throw new Exception("登录远程机器失败" + ip);
}
SCPClient sCPClient = conn.createSCPClient();
SCPOutputStream scpOutputStream = sCPClient.put(fileName, file.length(), remoteTargetDirectory, "0600");
String content = IOUtils.toString(new FileInputStream(file), StandardCharsets.UTF_8);
scpOutputStream.write(content.getBytes());
scpOutputStream.flush();
scpOutputStream.close();
}
/**
* 传输整个目录
*
* @param localDirectory
* @param remoteTargetDirectory
* @throws IOException
*/
public void transferDirectory(String localDirectory, String remoteTargetDirectory) throws Exception {
File dir = new File(localDirectory);
if (!dir.isDirectory()) {
throw new RuntimeException(localDirectory + " is not directory");
}
String[] files = dir.list();
for (String file : files) {
if (file.startsWith(".")) {
continue;
}
String fullName = localDirectory + "/" + file;
if (new File(fullName).isDirectory()) {
String rdir = remoteTargetDirectory + "/" + file;
exec("mkdir -p " + remoteTargetDirectory + "/" + file);
transferDirectory(fullName, rdir);
} else {
transferFile(fullName, remoteTargetDirectory);
}
}
}
public static void main(String args[]) throws Exception {
RemoteShellExecutor executor = new RemoteShellExecutor("120.25.233.237", "root", "5t8EsTuDH00uaA1");
executor.transferFile("3proxy.cfg", "/root");
// executor.execCommand("cd /root && sh restart.sh");
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment