aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/com/juick/server/api/ApiSocialLogin.java
blob: a2b80932ae4183170ee695c1bc8876f3a0f87d51 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
/*
 * Copyright (C) 2008-2019, Juick
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.juick.server.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.scribejava.apis.AppleClientSecretGenerator;
import com.github.scribejava.apis.AppleSignInApi;
import com.github.scribejava.apis.FacebookApi;
import com.github.scribejava.apis.VkontakteApi;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.model.OAuth2AccessToken;
import com.github.scribejava.core.model.OAuthRequest;
import com.github.scribejava.core.model.Verb;
import com.github.scribejava.core.oauth.OAuth20Service;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.juick.model.Auth;
import com.juick.model.facebook.User;
import com.juick.server.util.HttpBadRequestException;
import com.juick.service.CrosspostService;
import com.juick.service.EmailService;
import com.juick.service.UserService;
import com.juick.model.vk.UsersResponse;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.jwk.source.RemoteJWKSet;
import com.nimbusds.jose.proc.BadJOSEException;
import com.nimbusds.jose.proc.JWSKeySelector;
import com.nimbusds.jose.proc.JWSVerificationKeySelector;
import com.nimbusds.jose.proc.SecurityContext;
import com.nimbusds.jwt.proc.ConfigurableJWTProcessor;
import com.nimbusds.jwt.proc.DefaultJWTClaimsVerifier;
import com.nimbusds.jwt.proc.DefaultJWTProcessor;
import net.minidev.json.JSONObject;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.io.IOException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.text.ParseException;
import java.util.Collections;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutionException;

/**
 *
 * @author Ugnich Anton
 */
@Controller
public class ApiSocialLogin {

    private static final Logger logger = LoggerFactory.getLogger(ApiSocialLogin.class);

    @Value("${facebook_appid:appid}")
    private String FACEBOOK_APPID;
    @Value("${facebook_secret:secret}")
    private String FACEBOOK_SECRET;
    private static final String FACEBOOK_REDIRECT = "https://api.juick.com/_fblogin";
    private static final String VK_REDIRECT = "https://api.juick.com/_vklogin";
    private static final String TWITTER_VERIFY_URL = "https://api.twitter.com/1.1/account/verify_credentials.json";
    @Inject
    private ObjectMapper jsonMapper;
    private OAuth20Service facebookAuthService, vkAuthService, appleSignInService;

    @Value("${twitter_consumer_key:appid}")
    private String twitterConsumerKey;
    @Value("${twitter_consumer_secret:secret}")
    private String twitterConsumerSecret;
    @Value("${vk_appid:appid}")
    private String VK_APPID;
    @Value("${vk_secret:secret}")
    private String VK_SECRET;
    @Value("${google_client_id:}")
    private String googleClientId;
    @Value("${apple_app_id:appid}")
    private String appleApplicationId;
    @Value("${ap_base_uri:http://localhost:8080/}")
    private String baseUri;

    @Inject
    private CrosspostService crosspostService;
    @Inject
    private UserService userService;
    @Inject
    private EmailService emailService;
    @Inject
    private AppleClientSecretGenerator clientSecretGenerator;

    private final HttpTransport transport = new NetHttpTransport();
    private final JsonFactory jsonFactory = new JacksonFactory();
    private GoogleIdTokenVerifier verifier;

    @PostConstruct
    public void init() {
        ServiceBuilder facebookBuilder = new ServiceBuilder(FACEBOOK_APPID);
        ServiceBuilder twitterBuilder = new ServiceBuilder(twitterConsumerKey);
        ServiceBuilder vkBuilder = new ServiceBuilder(VK_APPID);
        verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory)
                .setAudience(Collections.singletonList(googleClientId))
                .build();
        facebookAuthService = facebookBuilder
                .apiSecret(FACEBOOK_SECRET)
                .callback(FACEBOOK_REDIRECT)
                .defaultScope("email")
                .build(FacebookApi.instance());
        vkAuthService = vkBuilder
                .apiSecret(VK_SECRET)
                .defaultScope("friends,wall,offline")
                .callback(VK_REDIRECT)
                .build(VkontakteApi.instance());
        ServiceBuilder appleSignInBuilder = new ServiceBuilder(appleApplicationId);
        UriComponentsBuilder redirectBuilder = UriComponentsBuilder.fromUriString(baseUri);
        String appleSignInRedirectUri = redirectBuilder.replacePath("/_apple").build().toUriString();
        appleSignInService = appleSignInBuilder
                .callback(appleSignInRedirectUri)
                .defaultScope("email")
                .build(new AppleSignInApi(clientSecretGenerator));
    }

    @GetMapping("/api/_fblogin")
    protected String doFacebookLogin(@RequestParam(required = false) String code,
                         @RequestParam(required = false) String state) throws IOException, ExecutionException, InterruptedException {
        if (StringUtils.isBlank(code)) {
            String fbstate = UUID.randomUUID().toString();
            crosspostService.addFacebookState(fbstate, state);
            return "redirect:" + facebookAuthService.getAuthorizationUrl(fbstate);
        }

        String redirectUrl = crosspostService.verifyFacebookState(state);

        if (StringUtils.isEmpty(redirectUrl)) {
            logger.error("state is missing");
            throw new HttpBadRequestException();
        }
        OAuth2AccessToken token = facebookAuthService.getAccessToken(code);
        final OAuthRequest meRequest = new OAuthRequest(Verb.GET, "https://graph.facebook.com/v3.2/me?fields=id,name,email");
        facebookAuthService.signRequest(token, meRequest);
        String graph = facebookAuthService.execute(meRequest).getBody();
        if (StringUtils.isBlank(graph)) {
            logger.error("FACEBOOK GRAPH ERROR");
            throw new HttpBadRequestException();
        }
        User fb = jsonMapper.readValue(graph, User.class);
        long fbID = NumberUtils.toLong(fb.getId(), 0);
        if (fbID == 0 || StringUtils.isBlank(fb.getName())) {
            logger.error("Missing required fields, id: {}, name: {}", fbID, fb.getName());
            throw new HttpBadRequestException();
        }

        int uid = crosspostService.getUIDbyFBID(fbID);
        if (uid > 0) {
            if (!crosspostService.updateFacebookUser(fbID, token.getAccessToken(), fb.getName())) {
                logger.error("error updating facebook user, id: {}, token: {}", fbID, token.getAccessToken());
                throw new HttpBadRequestException();
            }
            UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(redirectUrl);
            uriComponentsBuilder.queryParam("hash", userService.getHashByUID(uid));
            return "redirect:" + uriComponentsBuilder.build().toUriString();
        } else {
            if (!crosspostService.createFacebookUser(fbID, state, token.getAccessToken(), fb.getName())) {
                if (StringUtils.isNotEmpty(fb.getEmail())) {
                    logger.info("found {} for facebook user {}", fb.getEmail(), fb.getName());
                    Integer userId = crosspostService.getUIDbyFBID(fbID);
                    if (!emailService.getEmails(userId, false).contains(fb.getEmail())) {
                        emailService.addEmail(userId, fb.getEmail());
                    }
                }
                logger.info("email not found for facebook user {}", fb.getName());
                throw new HttpBadRequestException();
            }
            return "redirect:/signup?type=fb&hash=" + state;
        }
    }
    @GetMapping("/api/_vklogin")
    protected String doVKLogin(@RequestParam(required = false) String code,
                           @RequestParam String state) throws IOException, ExecutionException, InterruptedException {
        if (StringUtils.isBlank(code)) {
            String vkstate = UUID.randomUUID().toString();
            crosspostService.addVKState(vkstate, state);
            return "redirect:" + vkAuthService.getAuthorizationUrl(vkstate);
        }

        String redirectUrl = crosspostService.verifyVKState(state);
        if (StringUtils.isBlank(redirectUrl)) {
            logger.error("state is missing");
            throw new HttpBadRequestException();
        }
        OAuth2AccessToken token = vkAuthService.getAccessToken(code);

        OAuthRequest meRequest = new OAuthRequest(Verb.GET, "https://api.vk.com/method/users.get?fields=screen_name&v=5.73");
        vkAuthService.signRequest(token, meRequest);
        String graph = vkAuthService.execute(meRequest).getBody();

        com.juick.model.vk.User jsonUser = jsonMapper.readValue(graph, UsersResponse.class).getUsers().get(0);
        String vkName = jsonUser.getFirstName() + " " + jsonUser.getLastName();
        String vkLink = jsonUser.getScreenName();

        if (vkName.length() == 1 || StringUtils.isBlank(vkLink)) {
            logger.error("vk user error");
            throw new HttpBadRequestException();
        }

        long vkID = NumberUtils.toLong(jsonUser.getId(), 0);
        int uid = crosspostService.getUIDbyVKID(vkID);
        if (uid > 0) {
            UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(redirectUrl);
            uriComponentsBuilder.queryParam("hash", userService.getHashByUID(uid));
            return "redirect:" + uriComponentsBuilder.build().toUriString();
        } else {
            String loginhash = UUID.randomUUID().toString();
            if (!crosspostService.createVKUser(vkID, loginhash, token.getAccessToken(), vkName, vkLink)) {
                logger.error("create vk user error");
                throw new HttpBadRequestException();
            }
            return "redirect:/signup?type=vk&hash=" + loginhash;
        }
    }
    @ResponseBody
    @PostMapping("/api/_google")
    public ResponseEntity<Auth> googleSignIn(@RequestParam(name = "idToken") String idTokenString)
            throws GeneralSecurityException, IOException {
        logger.info("Token: {}", idTokenString);
        logger.info("Client: {}", googleClientId);
        GoogleIdToken idToken = verifier.verify(idTokenString);
        if (idToken != null) {
            String email = idToken.getPayload().getEmail();
            if (userService.getUserByEmail(email).isAnonymous()) {
                String verificationCode = RandomStringUtils.randomAlphanumeric(8).toUpperCase();
                emailService.addVerificationCode(null, email, verificationCode);
                return ResponseEntity.ok(new Auth(email, verificationCode));
            }
        }
        return ResponseEntity.status(HttpStatus.FORBIDDEN).body(null);
    }
    @ResponseBody
    @PostMapping("/api/signup")
    public ResponseEntity<com.juick.User> signupWithEmail(String username, String password, String verificationCode) {
        if (username.length() < 2 || username.length() > 16 || !username.matches("^[a-zA-Z0-9\\-]+$")
                || password.length() < 6 || password.length() > 32) {
            throw new HttpBadRequestException();
        }

        String verifiedEmail = emailService.getEmailByAuthCode(verificationCode);
        if (StringUtils.isNotEmpty(verifiedEmail)) {
            com.juick.User newUser = userService.createUser(username, password).orElseThrow(HttpBadRequestException::new);
            emailService.addEmail(newUser.getUid(), verifiedEmail);
            emailService.deleteAuthCode(verificationCode);
            return ResponseEntity.ok(newUser);
        } else {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(null);
        }
    }
    @GetMapping("/api/_apple")
    public String doAppleLogin(@RequestParam(required = false) String code, @RequestParam String state) {
        if (StringUtils.isBlank(code)) {
            String astate = UUID.randomUUID().toString();
            crosspostService.addVKState(astate, state);
            return "redirect:" + appleSignInService.getAuthorizationUrl(astate);
        }
        throw new HttpBadRequestException();
    }
    @PostMapping("/api/_apple")
    public String doVerifyAppleResponse(@RequestParam Map<String, String> body) throws InterruptedException, ExecutionException, IOException, ParseException, JOSEException, BadJOSEException {
        OAuth2AccessToken token = appleSignInService.getAccessToken(body.get("code"));
        var jsonNode = jsonMapper.readTree(token.getRawResponse());
        var idToken = jsonNode.get("id_token").textValue();

// Create a JWT processor for the access tokens
        ConfigurableJWTProcessor<SecurityContext> jwtProcessor =
                new DefaultJWTProcessor<>();

// The public RSA keys to validate the signatures will be sourced from the
// OAuth 2.0 server's JWK set, published at a well-known URL. The RemoteJWKSet
// object caches the retrieved keys to speed up subsequent look-ups and can
// also handle key-rollover
        JWKSource<SecurityContext> keySource =
                new RemoteJWKSet<>(new URL("https://appleid.apple.com/auth/keys"));

// The expected JWS algorithm of the access tokens (agreed out-of-band)
        JWSAlgorithm expectedJWSAlg = JWSAlgorithm.RS256;

// Configure the JWT processor with a key selector to feed matching public
// RSA keys sourced from the JWK set URL
        JWSKeySelector<SecurityContext> keySelector =
                new JWSVerificationKeySelector<>(expectedJWSAlg, keySource);

        jwtProcessor.setJWSKeySelector(keySelector);

// Set the required JWT claims for access tokens issued by the Connect2id
// server, may differ with other servers
        jwtProcessor.setJWTClaimsSetVerifier(new DefaultJWTClaimsVerifier<>());

// Process the token
        JSONObject claimsSet = jwtProcessor.process(idToken, null).toJSONObject();

        var email = claimsSet.getAsString("email");
        var verified = claimsSet.getAsString("email_verified").equals("true");

        if (verified) {
            com.juick.User user = userService.getUserByEmail(email);
            if (!user.isAnonymous()) {
                String redirectUrl = crosspostService.verifyVKState(body.get("state"));
                if (StringUtils.isBlank(redirectUrl)) {
                    logger.error("state is missing");
                    throw new HttpBadRequestException();
                }
                UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(redirectUrl);
                uriComponentsBuilder.queryParam("hash", userService.getHashByUID(user.getUid()));
                return "redirect:" + uriComponentsBuilder.build().toUriString();
            } else {
                String verificationCode = RandomStringUtils.randomAlphanumeric(8).toUpperCase();
                emailService.addVerificationCode(null, email, verificationCode);
                return "redirect:/signup?type=email&hash=" + verificationCode;
            }
        }
        throw new HttpBadRequestException();
    }
}