Skip to content

Instantly share code, notes, and snippets.

@anthonycvella
Created February 13, 2013 18:14
Show Gist options
  • Save anthonycvella/4946783 to your computer and use it in GitHub Desktop.
Save anthonycvella/4946783 to your computer and use it in GitHub Desktop.
Anthony Vella : Hiskor - Client/Server Architecture Code Note: I plan on moving my networking code to its own class once I finish working on my PHP backend.
<?php
require ('classes/database.php');
header("Content-type: text/json");
$dbinfo = array(
"host" => "127.0.0.1",
"user" => "root",
"pass" => "",
"name" => "hiskor"
);
// Creates the PDO Object for queries
$db = new Database ( $dbinfo );
$db->jsonError = true;
// Checks the type of request and redirects
$_POST['type'] = isset($_POST['type']) ? $_POST['type'] : null ;
switch ($_POST['type'])
{
case 'login':
login();
break;
case 'register':
register();
break;
}
function login()
{
global $db;
if (isset($_POST['username']) && isset($_POST['passwordMD5']))
{
//Put parameters into local variables
$username = $_POST['username'];
$passwordMD5 = $_POST['passwordMD5'];
// Gets the hashed password for the user in the database
$db->query("SELECT `password` FROM `users` WHERE `username`=?")->bind(1, $username)->execute();
if ($db->getTotalRows()) {
$result = $db->fetch();
$resultpassword = $result['password'];
}
// Checks if the hash sent from the client matches hash in database
if ($passwordMD5 == $resultpassword) {
$token = generateToken();
$db->query("UPDATE `users` SET `token` = ? WHERE `username`=?")->bind(1, $token)->bind(2, $username)->execute();
header('Content-type: application/json');
echo json_encode(array(
'username' => $username,
'token' => $token,
'message' => 'Success'
));
return true;
} else {
header('Content-type: application/json');
echo json_encode(array(
'message' => 'Failed'
));
return false;
}
}
return false;
}
function register()
{
global $db;
if (isset($_POST['username']) && isset($_POST['passwordMD5']) && isset($_POST['email']))
{
$username = $_POST['username'];
$passwordMD5 = $_POST['passwordMD5'];
$email = $_POST['email'];
$db->query("SELECT `username`, `email` FROM `users` WHERE `username=?` OR `email=?`")->bind(1, $username)->bind(2, $email)->execute();
if ($db->getTotalRows()) {
$result = $db->fetch();
}
if (!isset($result)) {
$db->query("INSERT INTO `users` (`username`, `password`, `email`) VALUES (`?`, `?`, `?`)")->bind(1, $username)->bind(2, $passwordMD5)->bind(3, $email)->execute();
header('Content-type: application/json');
echo json_encode(array(
'username' => $username,
'email' => $email,
'status' => 'Registration Passed'
));
return true;
} else {
header('Content-type: application/json');
echo json_encode(array(
'username' => $username,
'email' => $email,
'status' => 'Registration Failed'
));
return false;
}
}
return false;
}
// Generates random token for authentication sessions
function generateToken()
{
$token_length = 25;
$token = '';
for ($length = 0; $length < $token_length; $length++) {
$num = mt_rand(48, 122);
if ($num == '92') {
$num = '93';
}
$token .= chr($num);
}
return $token;
}
//
// LoginViewController.m
// Hiskor
//
// Created by Anthony Vella on 1/29/13.
// Copyright (c) 2013 ITP. All rights reserved.
//
#import "LoginViewController.h"
#import "AFHTTPClient.h"
#import "AFHTTPRequestOperation.h"
#import "AFJSONRequestOperation.h"
#import "Lockbox.h"
#import <CommonCrypto/CommonDigest.h>
#define kUsernameKeyString @"UsernameKeyString"
#define kTokenKeyString @"TokenKeyString"
#define kLoggedinStatusKeyString @"LoggedinStatusKeyString"
#define salt @"FSF^D&*FH#RJNF@!$JH#@$"
@interface LoginViewController ()
@end
@implementation LoginViewController
@synthesize usernameField, passwordField;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:@selector(dismissKeyboard)];
[self.view addGestureRecognizer:tap];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)dismissKeyboard {
[self.view endEditing:TRUE];
}
- (IBAction)btnLogin:(id)sender {
NSString *username = [usernameField text];
NSString *password = [passwordField text];
NSString *type = @"login";
// Hashing Algorithm
NSString *saltPassword = [password stringByAppendingString:salt];
NSString *passwordMD5 = [self md5:saltPassword];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
username, @"username",
passwordMD5, @"passwordMD5",
type, @"type",
nil];
// Sends request to server to login, server sends response via JSON
NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/Hiskor_Admin"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"api.php" parameters:params];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"Username: %@", [JSON valueForKeyPath:@"username"]);
NSLog(@"Token: %@", [JSON valueForKeyPath:@"token"]);
NSLog(@"Return Message: %@", [JSON valueForKeyPath:@"message"]);
if ([[JSON valueForKeyPath:@"message"] isEqualToString:@"Failed"]) {
UIAlertView *loginAlert = [[UIAlertView alloc] initWithTitle:@"Error logging in" message:@"Invalid username or password" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[loginAlert show];
} else {
UIAlertView *loginAlert = [[UIAlertView alloc] initWithTitle:@"Login Success" message:@"Proper login, thanks!" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[loginAlert show];
// Save username to keychain
[Lockbox setString:[JSON valueForKeyPath:@"username"] forKey:kUsernameKeyString];
// Save token to keychain
[Lockbox setString:[JSON valueForKeyPath:@"token"] forKey:kTokenKeyString];
// Save login status to keychain
[Lockbox setString:@"TRUE" forKey:kLoggedinStatusKeyString];
[self dismissViewControllerAnimated:YES completion:nil];
}
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"Error with request");
NSLog(@"%@", [error localizedDescription]);
}];
[operation start];
}
// Keychain Checker Function
- (IBAction)btnKeychainChecker:(id)sender {
NSLog(@"Keychain username: %@", [Lockbox stringForKey:kUsernameKeyString]);
NSLog(@"Keychain token: %@", [Lockbox stringForKey:kTokenKeyString]);
NSLog(@"Keychain login status: %@", [Lockbox stringForKey:kLoggedinStatusKeyString]);
}
// MD5 Hashing Function
- (NSString *)md5:(NSString *) input {
const char *cStr = [input UTF8String];
unsigned char digest[16];
CC_MD5(cStr, strlen(cStr), digest);
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
[output appendFormat:@"%02x", digest[i]];
}
return output;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment