Guest User

Untitled

a guest
Apr 24th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.50 KB | None | 0 0
  1. <?php
  2.  
  3. define('DB_NAME','android' );
  4. define('DB_USER','root');
  5. define('DB_PASSWORD','' );
  6. define('DB_HOST','localhost' );
  7.  
  8.  
  9. ?>
  10.  
  11. <?php
  12.  
  13. class Dbconnect{
  14.  
  15. private $con;
  16.  
  17. function __construct(){
  18.  
  19. }
  20.  
  21. function connect(){
  22. include_once dirname(__FILE__).'/constant.php';
  23. $this->con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
  24.  
  25. if(mysqli_connect_errno()){
  26. echo "Failed to connect with database".mysqli_connect_err();
  27. }
  28.  
  29. return $this->con;
  30. }
  31. }
  32.  
  33. <?php
  34.  
  35. class DbOperations{
  36.  
  37. private $con;
  38.  
  39. function __construct(){
  40.  
  41. require_once dirname(__FILE__).'/Dbconnect.php';
  42.  
  43. $db = new Dbconnect();
  44.  
  45. $this->con = $db->connect();
  46.  
  47. }
  48.  
  49. /*CRUD -> C -> CREATE */
  50.  
  51. public function createUser($username, $pass, $email){
  52. if($this->isUserExist($username,$email)){
  53. return 0;
  54. }else{
  55. $password = md5($pass);
  56. $stmt = $this->con->prepare("INSERT INTO `users` (`id`, `username`, `password`, `email`) VALUES (NULL, ?, ?, ?);");
  57. $stmt->bind_param("sss",$username,$password,$email);
  58.  
  59. if($stmt->execute()){
  60. return 1;
  61. }else{
  62. return 2;
  63. }
  64. }
  65.  
  66. }
  67.  
  68. public function userLogin($username, $pass){
  69. $password = md5($pass);
  70. $stmt = $this->con->prepare("SELECT id FROM users WHERE username = ?
  71. AND password = ?");
  72. $stmt->bind_param("ss",$username,$password);
  73. $stmt->execute();
  74. $stmt->store_result();
  75. return $stmt->num_rows > 0;
  76. }
  77.  
  78. public function getUserByUsername($username){
  79. $stmt = $this->con->prepare("SELECT * FROM users WHERE username = ?");
  80. $stmt->bind_param("s",$username);
  81. $stmt->execute();
  82. return $stmt->get_result()->fetch_assoc();
  83. }
  84.  
  85.  
  86. private function isUserExist($username, $email){
  87. $stmt = $this->con->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
  88. $stmt->bind_param("ss", $username, $email);
  89. $stmt->execute();
  90. $stmt->store_result();
  91. return $stmt->num_rows > 0;
  92. }
  93.  
  94. }
  95. ?>
  96.  
  97. <?php
  98.  
  99. require_once '../includes/DbOperations.php';
  100.  
  101. $response = array();
  102.  
  103. if($_SERVER['REQUEST_METHOD']=='POST'){
  104. if(
  105. isset($_POST['username']) and
  106. isset($_POST['email']) and
  107. isset($_POST['password']))
  108. {
  109. //operate the data further
  110.  
  111. $db = new DbOperations();
  112.  
  113. $result = $db->createUser( $_POST['username'],
  114. $_POST['password'],
  115. $_POST['email']
  116. );
  117. if($result == 1){
  118. $response['error'] = false;
  119. $response['message'] = "User registered successfully";
  120. }elseif($result == 2){
  121. $response['error'] = true;
  122. $response['message'] = "Some error occurred please try again";
  123. }elseif($result == 0){
  124. $response['error'] = true;
  125. $response['message'] = "It seems you are already registered, please choose a different email and username";
  126. }
  127.  
  128. }else{
  129. $response['error'] = true;
  130. $response['message'] = "Required fields are missing";
  131. }
  132. }else{
  133. $response['error'] = true;
  134. $response['message'] = "Invalid Request";
  135. }
  136.  
  137. echo json_encode($response);
  138.  
  139. <?php
  140.  
  141. require_once '../includes/DbOperations.php';
  142.  
  143. $response = array();
  144.  
  145. if($_SERVER['REQUEST_METHOD']=='POST'){
  146. if(isset($_POST['username']) and isset($_POST['password'])){
  147. $db = new DbOperations();
  148.  
  149. if($db->userLogin($_POST['username'], $_POST['password'])){
  150. $user = $db->getUserByUsername($_POST['username']);
  151. $response['error'] = false;
  152. $response['id'] = $user['id'];
  153. $response['email'] = $user['email'];
  154. $response['username'] = $user['username'];
  155. }else{
  156. $response['error'] = true;
  157. $response['message'] = "Invalid username or password";
  158. }
  159.  
  160. }else{
  161. $response['error'] = true;
  162. $response['message'] = "Required fields are missing";
  163. }
  164. }
  165.  
  166. echo json_encode($response);
  167.  
  168. package com.example.ahmad.volli;
  169.  
  170. import android.app.ProgressDialog;
  171. import android.content.Intent;
  172. import android.support.v7.app.AppCompatActivity;
  173. import android.os.Bundle;
  174. import android.view.View;
  175. import android.widget.Button;
  176. import android.widget.EditText;
  177. import android.widget.TextView;
  178. import android.widget.Toast;
  179.  
  180. import com.android.volley.AuthFailureError;
  181. import com.android.volley.Request;
  182. import com.android.volley.RequestQueue;
  183. import com.android.volley.Response;
  184. import com.android.volley.VolleyError;
  185. import com.android.volley.toolbox.StringRequest;
  186. import com.android.volley.toolbox.Volley;
  187.  
  188. import org.json.JSONException;
  189. import org.json.JSONObject;
  190.  
  191. import java.util.HashMap;
  192. import java.util.Map;
  193.  
  194. import static android.R.id.progress;
  195. import static com.example.ahmad.volli.R.id.textViewLogin;
  196.  
  197. public class MainActivity extends AppCompatActivity implements View.OnClickListener {
  198.  
  199. private EditText editTextUsername, editTextEmail, editTextPassword;
  200. private Button buttonRegister;
  201. private ProgressDialog progressDialog;
  202. private TextView textViewLogin;
  203. @Override
  204. protected void onCreate(Bundle savedInstanceState) {
  205. super.onCreate(savedInstanceState);
  206. setContentView(R.layout.activity_main);
  207.  
  208. if(SharedPrefManager.getInstance(this).isLoggedIn()){
  209. finish();
  210. startActivity(new Intent(this, ProfileActivity.class));
  211. return;
  212. }
  213.  
  214. editTextEmail = (EditText) findViewById(R.id.editTextEmail);
  215. editTextUsername = (EditText) findViewById(R.id.editTextUsername);
  216. editTextPassword = (EditText) findViewById(R.id.editTextPassword);
  217. textViewLogin = (TextView) findViewById(R.id.textViewLogin);
  218.  
  219. buttonRegister = (Button) findViewById(R.id.buttonRegister);
  220. progressDialog = new ProgressDialog(this);
  221. textViewLogin.setOnClickListener(this);
  222. buttonRegister.setOnClickListener(this);
  223.  
  224. }
  225. private void registerUser(){
  226. final String email = editTextEmail.getText().toString().trim() ;
  227. final String username = editTextUsername.getText().toString().trim();
  228. final String password = editTextPassword.getText().toString().trim();
  229. progressDialog.setMessage("Plz Wait");
  230. progressDialog.show();
  231.  
  232. StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.URL_REGISTER,
  233. new Response.Listener<String>() {
  234. @Override
  235. public void onResponse(String response) {
  236. progressDialog.dismiss();
  237.  
  238. try {
  239. JSONObject jsonObject = new JSONObject(response);
  240. Toast.makeText(getApplicationContext(),jsonObject.getString("message"),Toast.LENGTH_SHORT).show();
  241. } catch (JSONException e) {
  242. e.printStackTrace();
  243. }
  244. }
  245. },
  246. new Response.ErrorListener() {
  247. @Override
  248. public void onErrorResponse(VolleyError error) {
  249. progressDialog.hide();
  250. Toast.makeText(getApplicationContext(),error.getMessage(),Toast.LENGTH_LONG).show();
  251. }
  252. })
  253. {
  254. @Override
  255. protected Map<String, String> getParams() throws AuthFailureError {
  256. Map<String,String> params = new HashMap<>();
  257. params.put("username" ,username);
  258. params.put("email" ,email);
  259. params.put("password" ,password);
  260. return params;
  261.  
  262.  
  263. }
  264. };
  265.  
  266. RequestHandler.getInstance(this).addToRequestQueue(stringRequest);
  267.  
  268. }
  269.  
  270. @Override
  271. public void onClick(View view) {
  272. if (view == buttonRegister)
  273. registerUser();
  274. if (view == textViewLogin)
  275. {
  276. startActivity(new Intent(this,LoginActivity.class));
  277. }
  278.  
  279. }
  280. }
  281.  
  282. /**
  283. * Created by ahMad on 4/22/2018.
  284. */
  285.  
  286. public class Constants {
  287.  
  288. public static final String ROOT_URL = "http://172.21.34.7/Android/v1/";
  289.  
  290. public static final String URL_REGISTER = ROOT_URL+"registerUser.php";
  291. public static final String URL_LOGIN = ROOT_URL+"userLogin.php";
  292.  
  293. package com.example.ahmad.volli;
  294.  
  295. import android.app.ProgressDialog;
  296. import android.content.Intent;
  297. import android.support.v7.app.AppCompatActivity;
  298. import android.os.Bundle;
  299. import android.view.View;
  300. import android.widget.Button;
  301. import android.widget.EditText;
  302. import android.widget.Toast;
  303.  
  304. import com.android.volley.AuthFailureError;
  305. import com.android.volley.Request;
  306. import com.android.volley.Response;
  307. import com.android.volley.VolleyError;
  308. import com.android.volley.toolbox.StringRequest;
  309.  
  310. import org.json.JSONException;
  311. import org.json.JSONObject;
  312.  
  313. import java.util.HashMap;
  314. import java.util.Map;
  315.  
  316. public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
  317.  
  318. private EditText editTextUsername, editTextPassword;
  319. private Button buttonLogin;
  320. private ProgressDialog progressDialog;
  321.  
  322. @Override
  323. protected void onCreate(Bundle savedInstanceState) {
  324. super.onCreate(savedInstanceState);
  325. setContentView(R.layout.activity_login);
  326.  
  327. if(SharedPrefManager.getInstance(this).isLoggedIn()){
  328. finish();
  329. startActivity(new Intent(this, ProfileActivity.class));
  330. return;
  331. }
  332.  
  333. editTextUsername = (EditText) findViewById(R.id.editTextUsername);
  334. editTextPassword = (EditText) findViewById(R.id.editTextPassword);
  335. buttonLogin = (Button) findViewById(R.id.buttonLogin);
  336.  
  337. progressDialog = new ProgressDialog(this);
  338. progressDialog.setMessage("Please wait...");
  339. buttonLogin.setOnClickListener(this);
  340.  
  341. }
  342.  
  343. private void userLogin() {
  344. final String username = editTextUsername.getText().toString().trim();
  345. final String password = editTextPassword.getText().toString().trim();
  346.  
  347. progressDialog.show();
  348.  
  349. StringRequest stringRequest = new StringRequest(
  350. Request.Method.POST,
  351. Constants.URL_LOGIN,
  352. new Response.Listener<String>() {
  353. @Override
  354. public void onResponse(String response) {
  355. progressDialog.dismiss();
  356. try {
  357. JSONObject obj = new JSONObject(response);
  358. if(!obj.getBoolean("error")){
  359. SharedPrefManager.getInstance(getApplicationContext())
  360. .userLogin(
  361. obj.getInt("id"),
  362. obj.getString("username"),
  363. obj.getString("email")
  364. );
  365. startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
  366. finish();
  367. }else{
  368. Toast.makeText(
  369. getApplicationContext(),
  370. obj.getString("message"),
  371. Toast.LENGTH_LONG
  372. ).show();
  373. }
  374. } catch (JSONException e) {
  375. e.printStackTrace();
  376. }
  377. }
  378. },
  379. new Response.ErrorListener() {
  380. @Override
  381. public void onErrorResponse(VolleyError error) {
  382. progressDialog.dismiss();
  383.  
  384. Toast.makeText(
  385. getApplicationContext(),
  386. error.getMessage(),
  387. Toast.LENGTH_LONG
  388. ).show();
  389. }
  390. }
  391. ){
  392. @Override
  393. protected Map<String, String> getParams() throws AuthFailureError {
  394. Map<String, String> params = new HashMap<>();
  395. params.put("username", username);
  396. params.put("password", password);
  397. return params;
  398. }
  399.  
  400. };
  401. RequestHandler.getInstance(this).addToRequestQueue(stringRequest);
  402.  
  403.  
  404. }
  405.  
  406. @Override
  407. public void onClick(View view) {
  408. if(view == buttonLogin){
  409. userLogin();
  410. }
  411. }
  412. }
  413.  
  414. package com.example.ahmad.volli;
  415.  
  416. import android.content.Context;
  417. import android.content.SharedPreferences;
  418.  
  419. /**
  420. * Created by Belal on 26/11/16.
  421. */
  422.  
  423. public class SharedPrefManager {
  424. private static SharedPrefManager mInstance;
  425. private static Context mCtx;
  426.  
  427. private static final String SHARED_PREF_NAME = "mysharedpref12";
  428. private static final String KEY_USERNAME = "username";
  429. private static final String KEY_USER_EMAIL = "useremail";
  430. private static final String KEY_USER_ID = "userid";
  431.  
  432. private SharedPrefManager(Context context) {
  433. mCtx = context;
  434.  
  435. }
  436.  
  437. public static synchronized SharedPrefManager getInstance(Context context) {
  438. if (mInstance == null) {
  439. mInstance = new SharedPrefManager(context);
  440. }
  441. return mInstance;
  442. }
  443. public boolean userLogin(int id, String username, String email){
  444. SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
  445. SharedPreferences.Editor editor = sharedPreferences.edit();
  446.  
  447. editor.putInt(KEY_USER_ID, id);
  448. editor.putString(KEY_USER_EMAIL, email);
  449. editor.putString(KEY_USERNAME, username);
  450.  
  451. editor.apply();
  452.  
  453. return true;
  454. }
  455.  
  456. public boolean isLoggedIn(){
  457. SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
  458. if(sharedPreferences.getString(KEY_USERNAME, null) != null){
  459. return true;
  460. }
  461. return false;
  462. }
  463.  
  464. public boolean logout(){
  465. SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
  466. SharedPreferences.Editor editor = sharedPreferences.edit();
  467. editor.clear();
  468. editor.apply();
  469. return true;
  470. }
  471.  
  472. }
Add Comment
Please, Sign In to add comment