SocialLoginService sc = SocialLoginService.by(socialNetwork,appcode);
Token t =extractOAuthTokensFromRequest(request());
if(t==null){
return badRequest(String.format("Both %s and %s should be specified as query parameters or in the json body",OAUTH_TOKEN,OAUTH_SECRET));
}
UserInfo result=null;
try {
if(sc.validationRequest(t.getToken())){
result = sc.getUserInfo(t);
}else{
return badRequest("Provided token is not valid");
}
} catch (BaasBoxSocialException e1) {
return badRequest(e1.getError());
}catch (BaasBoxSocialTokenValidationException e2) {
return badRequest("Unable to validate provided token");
}
if (Logger.isDebugEnabled()) Logger.debug("UserInfo received: " + result.toString());
result.setFrom(socialNetwork);
result.setToken(t.getToken());
//Setting token as secret for one-token only social networks
result.setSecret(t.getSecret()!=null && StringUtils.isNotEmpty(t.getSecret())?t.getSecret():t.getToken());
UserDao userDao = UserDao.getInstance();
ODocument existingUser = null;
try{
existingUser = userDao.getBySocialUserId(result);
}catch(SqlInjectionException sie){
return internalServerError(sie.getMessage());
}
if(existingUser!=null){
String username = null;
try {
username = UserService.getUsernameByProfile(existingUser);
if(username==null){
throw new InvalidModelException("username for profile is null");
}
} catch (InvalidModelException e) {
internalServerError("unable to login with "+socialNetwork+" : "+e.getMessage());
}
String password = generateUserPassword(username, (Date)existingUser.field(UserDao.USER_SIGNUP_DATE));
ImmutableMap<SessionKeys, ? extends Object> sessionObject = SessionTokenProvider.getSessionTokenProvider().setSession(appcode,username, password);
response().setHeader(SessionKeys.TOKEN.toString(), (String) sessionObject.get(SessionKeys.TOKEN));
ObjectNode on = Json.newObject();
if(existingUser!=null){
on = (ObjectNode)Json.parse( User.prepareResponseToJson(existingUser));
}
on.put(SessionKeys.TOKEN.toString(), (String) sessionObject.get(SessionKeys.TOKEN));
return ok(on);
}else{
if (Logger.isDebugEnabled()) Logger.debug("User does not exists with tokens...trying to create");
String username = UUID.randomUUID().toString();
Date signupDate = new Date();
try{
String password = generateUserPassword(username, signupDate);
JsonNode privateData = null;
if(result.getAdditionalData()!=null && !result.getAdditionalData().isEmpty()){
privateData = Json.toJson(result.getAdditionalData());
}
UserService.signUp(username, password, signupDate, null, privateData, null, null,true);
ODocument profile=UserService.getUserProfilebyUsername(username);
UserService.addSocialLoginTokens(profile,result);
ImmutableMap<SessionKeys, ? extends Object> sessionObject = SessionTokenProvider.getSessionTokenProvider().setSession(appcode, username, password);