Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
- (void)performVKLogin
{
@weakify(self);
id conf = @{
LMAVkontakteSDKClientId : __YOUR_APP_ID__,
LMAVkontakteSDKScope : @[ VK_PER_WALL, VK_PER_STATUS, VK_PER_EMAIL ],
LMAVkontakteSDKRevokeAccess : @NO,
LMAVkontakteSDKForceOAuth : @YES,
LMAVkontakteSDKAuthorizeInApp : @YES
};
// authController живёт в AppDelegate
id<LMARequest> request = [authController authorizeWithProvider:@"vkontakte" configuration:conf completionHandler:^(NSDictionary *credential, NSError *error) {
if (error)
{
@strongify(self);
[self showError:error title:@"Ошибка входа"];
return;
}
if (!credential)
{
NSLog(@"User cancelled login!");
return;
}
NSLog(@"Finished vkontakte auth: %@", credential);
// тут сохраняю credential
[VKSdk wakeUpSession];
VKRequest *req = [[VKApi users] get];
[req executeWithResultBlock:^(VKResponse *response) {
@strongify(self);
NSString *firstName = response.json[0][@"first_name"];
NSString *lastName = response.json[0][@"last_name"];
NSString *fullName = [NSString stringWithFormat:@"%@ %@", firstName, lastName];
NSString *email = credential[@"email"]
// тут сохраняю данные юзера
[self showGreetings:fullName];
} errorBlock:^(NSError *reqError) {
@strongify(self);
[self showError:reqError title:@"Ошибка запрса данных"];
}];
}];
[request start];
}
- (void)performTwitterLogin
{
@weakify(self);
id conf = @{
LMATwitterSTConsumerKey : __YOUR_APP_KEY__,
LMATwitterSTConsumerSecret : __YOUR_APP_SECRET__,
LMATwitterSTCallbackURL : @"__YOUR_APP_SCHEME__://twitter"
};
id<LMARequest> request = [authController authorizeWithProvider:@"twitter" configuration:conf completionHandler:^(NSDictionary *credential, NSError *error) {
if (error)
{
@strongify(self);
[self showError:error title:@"Ошибка входа"];
return;
}
if (!credential)
{
NSLog(@"User cancelled login!");
return;
}
NSLog(@"Finished twitter auth: %@", credential);
// опять сохраняю credential
self.twitter = [STTwitterAPI twitterAPIWithOAuthConsumerKey:__YOUR_APP_KEY__ consumerSecret:__YOUR_APP_SECRET__ oauthToken:credential[@"oauth_token"] oauthTokenSecret:credential[@"oauth_token_secret"]];
[self.twitter getUsersShowForUserID:nil orScreenName:credential[@"screen_name"] includeEntities:nil successBlock:^(NSDictionary *user) {
NSString *name = user[@"name"];
NSString *screenName = user[@"screen_name"];
// сохраняю данные юзера
@strongify(self);
[self showGreetings:name];
} errorBlock:^(NSError *getError) {
@strongify(self);
[self showError:getError title:@"Ошибка запроса данных"];
}];
}];
[request start];
}
- (void)performGooglePlusLogin
{
@weakify(self);
id conf = @{
LMAGooglePlusSDKClientId : __YOUR_APP_ID__,
LMAGooglePlusSDKScope : @[ kGTLAuthScopePlusLogin, kGTLAuthScopePlusMe, kGTLAuthScopePlusUserinfoEmail, kGTLAuthScopePlusUserinfoProfile ]
};
id<LMARequest> request = [authController authorizeWithProvider:@"googleplus" configuration:conf completionHandler:^(NSDictionary *credential, NSError *error) {
if (error)
{
@strongify(self);
[self showError:error title:@"Ошибка входа"];
return;
}
if (!credential)
{
NSLog(@"User cancelled login!");
return;
}
// сохраняю credential
GTLServicePlus *plusService = [GTLServicePlus new];
[plusService setAuthorizer:[MYGooglePlusAuth new]];
GTLQueryPlus *query = [GTLQueryPlus queryForPeopleGetWithUserId:@"me"];
[plusService executeQuery:query completionHandler:^(GTLServiceTicket *__unused ticket, GTLPlusPerson *person, NSError *queryError) {
if (queryError)
{
[self showError:queryError title:@"Ошибка запроса данных"];
}
else
{
GTLPlusPersonEmailsItem *emailItem = person.emails[0];
NSString *displayName = person.displayName;
NSString *email = emailItem.value;
NSString *profileUrl = person.url;
// сохраняю данные
@strongify(self);
[self showGreetings:person.displayName];
}
}];
}];
[request start];
}
- (void)performFacebookLogin
{
@weakify(self);
id conf = @{
LMAFacebookSDKAppId : __YOUR_APP_ID__,
LMAFacebookSDKPermissions : @[ @"public_profile", @"email", @"user_friends" ],
LMAFacebookSDKURLSchemeSuffix : @"",
LMAFacebookSDKAudience : LMAFacebookSDKAudienceEveryone
};
id<LMARequest> request = [authController authorizeWithProvider:@"facebook" configuration:conf completionHandler:^(NSDictionary *credential, NSError *error) {
if (error)
{
@strongify(self);
[self showError:error title:@"Ошибка входа"];
return;
}
if (!credential)
{
NSLog(@"User cancelled login!");
return;
}
// сохраняю credential
id completionBlock = ^(FBSession *__unused session, FBSessionState __unused status, NSError *__unused openError) {
if (openError)
{
@strongify(self);
[self showError:openError title:@"Ошибка запроса данных"];
return;
}
[[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *__unused connection, NSDictionary<FBGraphUser> *user, NSError *reqError) {
@strongify(self);
if (!reqError)
{
NSString *name = user.name;
NSString *email = user[@"email"];
// сохраняю данные
[self showGreetings:user.name];
}
else
{
[self showError:reqError title:@"Ошибка запроса данных"];
}
}];
};
if (FBSession.activeSession.state == FBSessionStateCreatedTokenLoaded)
{
[FBSession.activeSession openWithCompletionHandler:completionBlock];
}
else
{
FBAccessTokenData *td = [FBAccessTokenData createTokenFromString:credential[@"access_token"]
permissions:credential[@"scope"]
declinedPermissions:@[]
expirationDate:credential[@"expires_at"]
loginType:FBSessionLoginTypeNone
refreshDate:nil
permissionsRefreshDate:nil
appID:nil
userID:nil];
[FBSession.activeSession openFromAccessTokenData:td completionHandler:completionBlock];
}
}];
[request start];
}
// класс MYGooglePlusAuth — для авторизации через G+
@interface MYGooglePlusAuth : NSObject <GTMFetcherAuthorizationProtocol>
@end
@interface MYGooglePlusAuth ()
@property (nonatomic, strong) NSString *accessToken;
@end
@implementation MYGooglePlusAuth
@synthesize userEmail;
- (instancetype)init
{
self = [super init];
if (self)
{
self.accessToken = [[MYSettings sharedInstance] loginCredentials][@"googleplus"][@"access_token"];
}
return self;
}
#pragma mark - GTMFetcherAuthorizationProtocol
- (void)authorizeRequest:(NSMutableURLRequest *)request delegate:(id)delegate didFinishSelector:(SEL)sel
{
if (request)
{
NSString *value = [NSString stringWithFormat:@"%s %@", GTM_OAUTH2_BEARER, self.accessToken];
[request setValue:value forHTTPHeaderField:@"Authorization"];
}
NSMethodSignature *sig = [delegate methodSignatureForSelector:sel];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig];
[invocation setSelector:sel];
[invocation setTarget:delegate];
[invocation setArgument:(__bridge void *)(self) atIndex:2];
[invocation setArgument:&request atIndex:3];
[invocation invoke];
}
- (void)authorizeRequest:(NSMutableURLRequest *)request completionHandler:(void (^)(NSError *error))__unused handler
{
if (request)
{
NSString *value = [NSString stringWithFormat:@"%@ %@", @"Bearer", self.accessToken];
[request setValue:value forHTTPHeaderField:@"Authorization"];
}
}
- (BOOL)isAuthorizedRequest:(NSURLRequest *)__unused request
{
return NO;
}
- (void)stopAuthorization
{
}
- (void)stopAuthorizationForRequest:(NSURLRequest *)__unused request
{
}
- (BOOL)isAuthorizingRequest:(NSURLRequest *)__unused request
{
return YES;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.