Placement of Login code to website using Facebook account - facebook-javascript-sdk

Hi I'm new to web development. I would like to code for Login to website using Facebook account which I know that I need to add this js to install the Facebook SDK:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'your-app-id',
xfbml : true,
version : 'v2.4'
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
However, I'm unsure on where to put it. It was mentioned that I should insert it directly after the opening <body> tag on each page I want to load it. However, Both of my register and login.php were done in floating div. There's no <body> tag. Hence, I not sure where to add this code in too:
<?php
if(!isset($_SESSION))
{
session_start();
}
require_once('config.php');
require_once('facebook.php');
require_once('PHPMailer/PHPMailerAutoload.php');
$facebook = new Facebook($config);
$fbUser = $facebook->getUser();
$_SESSION[$PROJECT_NAME . '-allowUser'] = true;
$uri = explode('/', strtok($_SERVER["REQUEST_URI"],'?'));
if ($fbUser) {
$user_profile = $facebook->api('/me');
$fbEmail = $user_profile["email"];
$fbId = $user_profile["id"];
}
Below is my login.php.
login.php
<div id="loginScreen">
<div class="xclose">
<em>×</em>
</div>
<div id="loghead">Facebook Connect</div>
<div class="articlepreview">
<form name="loginForm" method="post" id="registrationForm"
action="processLogin">
<div class="signintitle">Sign in to your Account</div>
<div class="form-group">
<input class="emailaddr" type="email" name="emailaddr" required
id="emailaddr" placeholder="Email Address"> <br> <input
type="password" name="password" required class="password"
id="id_password" placeholder=Password
<?php
if (preg_match ( "/^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/", $password )) {
echo "Your passwords is strong.";
} else {
echo "Your password is weak.";
}
?>
required>
</div>
<br>
<center>
<input class="greybtn" type="submit" value="Sign in" name="signin">
</center>
<div class="forgotpw" style="text-align: center;">
<br> Forgot Password? <br>
Create an Account <br>
</div>
</form>
</div>

Related

ASP.NET Core Razor Page, code behind method not being triggered

I have a C# Razor Pages project.
I created a Login view in the following structure:
- Pages
- Account
- Login.cshtml
This is the code for my Login view
#page "{handler?}"
#model HAL_WEB.Pages.LoginModel
#{
Layout = "_LayoutLogin";
}
<section class="section register min-vh-100 d-flex flex-column align-items-center justify-content-center py-4">
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-4 col-md-6 d-flex flex-column align-items-center justify-content-center">
<div class="d-flex justify-content-center py-4">
<a href="index.html" class="logo d-flex align-items-center w-auto">
<img src="assets/img/teamtruetech_logo.png" alt="">
<span class="d-none d-lg-block">HAL Admin</span>
</a>
</div><!-- End Logo -->
<div class="card mb-3">
<div class="card-body">
<div class="pt-4 pb-2">
<h5 class="card-title text-center pb-0 fs-4">Login to Your Account</h5>
<p class="text-center small">Enter your username & password to login</p>
</div>
<form id="login-form" class="row g-3 needs-validation" novalidate>
<div class="col-12">
<label for="yourUsername" class="form-label">Username</label>
<div class="input-group has-validation">
<span class="input-group-text" id="inputGroupPrepend"></span>
<input type="text" name="username" class="form-control" id="yourUsername" required>
<div class="invalid-feedback">Please enter your username.</div>
</div>
</div>
<div class="col-12">
<label for="yourPassword" class="form-label">Password</label>
<input type="password" name="password" class="form-control" id="yourPassword" required>
<div class="invalid-feedback">Please enter your password!</div>
</div>
<div class="col-12">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" value="true" id="rememberMe">
<label class="form-check-label" for="rememberMe">Remember me</label>
</div>
</div>
<div class="col-12">
<button class="btn btn-primary w-100" type="submit">Login</button>
</div>
#* <div class="col-12">
<p class="small mb-0">Don't have account? Create an account</p>
</div>*#
</form>
</div>
</div>
</div>
</div>
</div>
</section>
#section Scripts {
<script src="~/assets/js/loginpage.js"></script>
}
And this is the code behind:
using HAL_WEB.Data;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Security.Claims;
namespace HAL_WEB.Pages
{
public class LoginModel : PageModel
{
private readonly ApplicationDBContext _dbContext;
public LoginModel([FromServices] ApplicationDBContext dbContext)
{
_dbContext = dbContext;
}
public void OnGet()
{
}
public async Task<IActionResult> OnPostLoginAsync(string username, string password)
{
// Check if the provided credentials are valid
if (IsValidCredentials(username, password))
{
// If the credentials are valid, log the user in
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, username) }, CookieAuthenticationDefaults.AuthenticationScheme)),
new AuthenticationProperties
{
IsPersistent = true, // Set this to true if you want the user to stay logged in after closing the browser
ExpiresUtc = DateTime.UtcNow.AddDays(7) // Set the expiration time for the cookie
});
// Redirect the user to the home page
return RedirectToPage("/Home");
}
else
{
// If the credentials are invalid, show an error message
ModelState.AddModelError(string.Empty, "Invalid username or password.");
return Page();
}
}
private bool IsValidCredentials(string username, string password)
{
// Replace this with your own validation logic
return username == "admin" && password == "password";
}
public IActionResult OnPostLoginTestAsync()
{
return new JsonResult(true);
}
}
In my Javascript file I tried to call the method OnPostLoginTestAsync or OnPostLoginAsync without success.
I'm getting a "Bad Request 400" error:
This is my Javascript Axios code for calling the method:
// Use Axios to send a POST request to the server with the form data
axios.post('/Account/Login?handler=login', {
username,
password,
})
.then((response) => {
// If the request is successful, redirect the page
window.location.href = '/home';
})
.catch((error) => {
// If there is an error, log it to the console
console.error(error);
});
Any clue what am I doing wrong? I'm going to /Account/Login?handler=login because the call is a Post and what I think is that the method OnPostLoginAsync should be executed.
UPDATE
I found something interesting, I created the following Get method:
public IActionResult OnGetTestAsync()
{
return new JsonResult(true);
}
And in my Javascript, I changed the Axios url to be:
axios.get('/Account/Login?handler=test')
.then(function (response) {
})
.catch(function (error) {
// Handle the error response
});
And I could get the method executed! But when I change the method name back to:
OnPostTestAsync
and my Axios to:
axios.post('/Account/Login?handler=test')
.then(function (response) {
})
.catch(function (error) {
// Handle the error response
});
It never gets executed and I get 400 Bad Request. Any clue?

controller not sending to view .net core

controller not sending to view . I m trying to send request from controller to view , but its not redirecting . controller always redirect to index page. when i summit the form . its always redirecting same index page ,
controller not sending to view .controller not sending to view
My controller is sending to another view. but its not working .
public IActionResult userLogin([FromBody] Users user)
{
string apiUrl = "https://localhost:44331/api/ProcessAPI";
var input = new
{
email = user.email,
password = user.password
};
string inputJson = (new JavaScriptSerializer()).Serialize(input);
WebClient client = new WebClient();
client.Headers["Content-type"] = "application/json";
// client.Encoding = Encoding.UTF8;
string json = client.UploadString(apiUrl + "/userLogin", inputJson);
// List<Users> customers = (new JavaScriptSerializer()).Deserialize<List<Users>>(json);
user = JsonConvert.DeserializeObject<Users>(json);
return View();
}
and the view page is
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#model myproject.Models.Users
#{
Layout = null;
}
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Inventory Management System</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
#* <link rel="stylesheet" type="text/css" href="./includes/style.css">*#
#*<script type="text/javascript" rel="stylesheet" src="~/js/main.js"></script>*#
</head>
<body>
<div class="overlay"><div class="loader"></div></div>
<!-- Navbar -->
<br /><br />
<div class="container">
<div class="alert alert-success alert-dismissible fade show" role="alert">
#*<?php echo $_GET["msg"]; ?>*#
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#*<?php
}
?>*#
<div class="card mx-auto" style="width: 20rem;">
<img class="card-img-top mx-auto" style="width:60%;" src="./images/login.png" alt="Login Icon">
<div class="card-body">
<form id="form_login" >
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
#*<input asp-for="Name" type="text" class="form-control" id="name" required />*#
<input asp-for="email" type="email" class="form-control" id="log_email" placeholder="Enter email">
<small id="e_error" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" name="log_password" asp-for="password" id="log_password" placeholder="Password">
<small id="p_error" class="form-text text-muted"></small>
</div>
<button type="submit" class="btn btn-primary"><i class="fa fa-lock"> </i>Login</button>
<span>Register</span>
</form>
</div>
<div class="card-footer">Forget Password ?</div>
</div>
</div>
<input type="text" id="txtName" />
<input type="button" id="btnGet" value="Get Current Time" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#form_login").on("submit", function () {
var data = {
email: $("#log_email").val(),
password: $("#log_password").val(),
// Phone: $("#phone").val()
}
// data: $("#form_login").serialize(),
// var data = $("#form_login").serialize();
console.log(data);
$.ajax({
type: 'POST',
url: '/Process/userLogin',
// window.location.href = '#Url.Action("Process", "Dashboard")';
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
success: function (result) {
alert('Successfully received Data ');
console.log(result);
window.location.href = "Process/Dashboard";
// window.location.href = '#Url.Content("~/User/Home")';
// window.location.href = '#Url.Action("Process", "Dashboard")';
// window.location.href = DOMAIN + "/dashboard.php";
},
error: function () {
alert('Failed to receive the Data');
console.log('Failed ');
}
})
})
});
</script>
</body>
</html>
From your code, since you want to use JQuery Ajax to submit the form data to the action method, in the form submit event, you should use the event.preventDefault() to prevent the form submit action, then you can use JQuery Ajax to submit the form.
Second, does the Index page is the Process/Dashboard page? From your code, we can see in the Ajax success function, you will use the window.location.href to change the request URL, you can change the redirect page from here.

Bootstrap 4.3.1 dropdown login form redirect upon success

I am building a site where users can login via a Bootstrap Dropdown, i did have it working, it would log user in and refresh the whole page with login session BUT if user entered wrong creds it wouldn't stay open and alert them. I got around this by putting the login form in an iframe in the dropdown but it's no longer starting the session - any ideas please? I'm trying to not be vague so here is the code in the iframe and the actual URL below that - thank you :)
<div class="header_login_form_dropdown">Login</div>
<form name="login" action="" method="post" class="form">
<div class="form-group">
<label class="login_form_dropdown" for="lopc_username">Email</label>
<input type="email" class="form-control" id="lopc_username" placeholder="email#company.com" name="lopc_username">
</div>
<div class="form-group">
<label class="login_form_dropdown" for="lopc_password">Password</label>
<input type="password" class="form-control" id="lopc_password" name="lopc_password">
</div>
Forgot password
<button type="submit" name="submit" class="btn btn-primary login_btn">LOGIN</button>
<div style="padding:15px 0 15px 0; border-top: 2px solid #eee; font-size: 14px; color: #696969">
New customer? Register here
</div>
<?php
if (isset($_POST['submit']))
{
include('../265451/92631043.php');
$lopc_username = mysqli_real_escape_string($conn,$_POST['lopc_username']);
$lopc_password = mysqli_real_escape_string($conn,(md5($_POST['lopc_password'])));
$lopc_last_login = date("Y-m-d H:i:s");
$query = "SELECT * FROM lopc_reg_users WHERE lopc_username = '$lopc_username' AND lopc_password = '$lopc_password' ";
$result = mysqli_query($conn,$query);
if(mysqli_num_rows($result) == 1)
{
$_SESSION['lopc_username'] = $_POST['lopc_username'];
$lopc_username = $_SESSION['lopc_username'];
$query2 = "UPDATE lopc_reg_users SET lopc_last_login = '$lopc_last_login' WHERE lopc_username = '$lopc_username' ";
$result2 = mysqli_query($conn,$query2);
//header("Location: ".$_SERVER['PHP_SELF']);
?>
<script>
window.parent.location.reload();
</script>
<?php
exit;
}
else
{
echo '<div class="login_error">Username or password does not exist.</div>';
}
}
?>
</form>
https://littleorangeprinting.co.uk/2021
Login: test#test.com
Pass: testing4321

Aurelia -- Route Change on Form Submission Issue

Aurelia newbie here and I have hit a wall.
So, this code works just fine and the route change happens, but it only happens after the Submit button on the home.html file is clicked TWICE. On the first Submit button click, I get the following error: ERROR [app-router] Error: Route not found: /anonymous-wow-armory-profile/.
My question is why does it work after two form submissions, but not the first one? I know I am missing something in the process here.
home.html
<template>
<div class="container-fluid">
<div class="row">
<div class="col-md-12 nav-home text-center">
Create Profile
Bug Report
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="logo">
<img src="dist/assets/images/logo.png" alt="Logo" />
</div>
</div>
</div>
<div class="row row-bottom-pad">
<div class="col-md-4"></div>
<div class="col-md-4">
<div class="profile-creation-box">
<div class="box-padding">
<strong>Masked Armory</strong> is the most well known anonymous World of Warcraft (WoW) profile source in the Real Money Trading (RMT) market. We take everything to the next level with offering alternate gear sets, sorted reputation display, Feat of Strength / Legacy achievement display, and much more!<br /><br />
Come make a profile at Masked Armory today and see that we are the best solution for all of your anonymous WoW Armory profile needs!
</div>
</div>
</div>
<div class="col-md-4"></div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4 container-bottom-pad">
<div class="profile-creation-box">
<div class="box-padding">
<form class="form-horizontal" role="form" submit.delegate="submit()">
<div class="form-group">
<label class="col-sm-3 control-label">Region</label>
<div class="col-sm-9">
<label class="radio-inline">
<input type="radio" name="region_name" value="us" checked.bind="postData.region"> United States
</label>
<label class="radio-inline">
<input type="radio" name="region_name" value="eu" checked.bind="postData.region"> Europe
</label>
</div>
</div>
<div class="form-group">
<label for="server_name" class="col-sm-3 control-label">Server</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="server_name" placeholder="Server Name" value.bind="postData.serverName">
</div>
</div>
<div class="form-group">
<label for="character_name" class="col-sm-3 control-label">Character</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="character_name" name="character_name" placeholder="Character Name" value.bind="postData.characterName">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9">
<div class="checkbox">
<label>
<input type="checkbox" id="altgear" name="altgear"> Add Alternate Gearset
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9">
<button type="submit" class="btn btn-danger">Create Armory Profile</button>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="col-md-4"></div>
</div>
</div>
</template>
home.js
import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-http-client';
import {Router} from 'aurelia-router';
#inject(Router)
export class Home {
postData: Object = {};
data: string = '';
code: string = '';
loading: boolean = false;
http: HttpClient = null;
apiUrl: string = 'http://localhost:8000/api/v1';
constructor(router) {
this.http = new HttpClient().configure(x => {
x.withBaseUrl(this.apiUrl);
x.withHeader('Content-Type', 'application/json');
});
this.maRouter = router;
}
submit() {
console.log(this.postData);
this.http.post('/armory', JSON.stringify(this.postData)).then(response => {
this.data = response.content;
this.code = response.statusCode.toString();
this.loading = false;
});
this.maRouter.navigateToRoute('armory', {id: this.data});
}
}
armory.js
import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-http-client';
export class Armory {
postData: Object = {};
data: string = '';
code: string = '';
loading: boolean = false;
http: HttpClient = null;
apiUrl: string = 'http://localhost:8000/api/v1';
profileId: number = 0;
constructor() {
this.loading = true;
this.http = new HttpClient().configure(x => {
x.withBaseUrl(this.apiUrl);
x.withHeader('Content-Type', 'application/json');
});
}
activate(params, routeConfig) {
this.profileId = params.id;
this.getArmoryData();
}
getArmoryData() {
return this.http.get("/armory/" + this.profileId).then(response => {
this.data = response.content;
console.log(this.data);
this.code = response.statusCode.toString();
this.loading = false;
});
}
}
What am I missing here?
Thanks for your help!
Please, provide your router configuration
Anyway I see some issues already. You try to navigate when this.data is not set, just wait for response:
this.http.post('/armory', JSON.stringify(this.postData)).then(response => {
this.data = response.content;
this.code = response.statusCode.toString();
this.loading = false;
this.maRouter.navigateToRoute('armory', {id: this.data});
});
and we do activate page only if this.getArmoryData() succeed here (if needed), also canActivate() maybe used too
activate(params, routeConfig) {
this.profileId = params.id;
return this.getArmoryData();
}
also would be better to set this.loading = true;, inside armory .activate() and in home.js in submit() before sending data

Multer can not get the upload form data in Express 4

I'm using Ajax to upload the form data. The output of multer(req.file, req.body) is always undefined/{};
My server code:
import multer from 'multer';
import post from './router/api_post';
var upload = multer({dest: 'uploads/'});
app.use('/api/post', upload.single('thumb') , post);
and the api_post router file:
import express from 'express';
var router = express.Router();
router
.post('/', (req, res, next) => {
console.log("POST POST");
var post = {};
console.log(req.body);
console.log(req.file);
});
export default router;
the output of req.body is {} and of req.fileisundefined`.
I use react on the browser side and upload data via ajax:
savePost(ev) {
ev.preventDefault();
var editor = this.refs.editorDom.getDOMNode();
var ajaxReq = new AjaxRequest();
var formData = new FormData();
formData.append('post_id', this.state.post_id);
formData.append('title', this.state.title);
formData.append('author', this.state.author);
formData.append('digest', this.state.digest);
formData.append('content', editor.innerHTML);
formData.append('content_source_url', this.state.content_source_url);
formData.append('create_time', new Date());
formData.append('thumb', this.state.thumb);
ajaxReq.send('post', '/api/post', ()=>{
if(ajaxReq.getReadyState() == 4 && ajaxReq.getStatus() == 200) {
var result = JSON.parse(ajaxReq.getResponseText());
if(result.ok == 1) {
console.log("SAVE POST SUCCESS");
}
}
}, '', formData);
}
The savePost() is callback of a button's event listener. I did upload data successfully with formidable. I just replaced the formidable with multer but can not get it.
I didn't set the content-type property. I found it in the header is
, multipart/form-data; boundary=----WebKitFormBoundary76s9Cg74EW1B94D9
The form's HTML is
<form id="edit-panel" data-reactid=".ygieokt1c0.1.0.1.0.1">
<div id="title" class="form-group" data-reactid=".ygieokt1c0.1.0.1.0.1.0">
<input type="text" class="form-control" name="title" value="" data-reactid=".ygieokt1c0.1.0.1.0.1.0.1">
</div>
<div id="author" class="form-group" data-reactid=".ygieokt1c0.1.0.1.0.1.1">
<input type="text" class="form-control" name="author" value="" data-reactid=".ygieokt1c0.1.0.1.0.1.1.1">
</div>
<div id="thumb" class="form-group" data-reactid=".ygieokt1c0.1.0.1.0.1.2">
<button class="btn btn-default" data-reactid=".ygieokt1c0.1.0.1.0.1.2.1">
<input type="file" name="thumb" accept="image/*" data-reactid=".ygieokt1c0.1.0.1.0.1.2.1.0">
<span data-reactid=".ygieokt1c0.1.0.1.0.1.2.1.1">UPLOAD</span>
</button>
</div>
<div class="form-group" data-reactid=".ygieokt1c0.1.0.1.0.1.3">
<textarea class="form-control" name="digest" rows="5" data-reactid=".ygieokt1c0.1.0.1.0.1.3.1"></textarea>
</div>
<div id="rich-text-editor" class="form-group" data-reactid=".ygieokt1c0.1.0.1.0.1.4">
<div id="editor-div" class="form-control" contenteditable="true" data-reactid=".ygieokt1c0.1.0.1.0.1.4.1"></div>
</div>
<div id="content-source-url" class="form-group" data-reactid=".ygieokt1c0.1.0.1.0.1.5">
<input type="text" class="form-control" name="content_source_url" value="" data-reactid=".ygieokt1c0.1.0.1.0.1.5.1">
</div>
<button class="btn btn-default" data-reactid=".ygieokt1c0.1.0.1.0.1.6">保存并提交</button>
</form>
I can output the thumb, it's a File{} object.
Thanks for help.
Finally I found the problem is the Content-Type.
I used this.request.setRequestHeader("Content-Type", postDataType); to set the Content-Type and set the postDataType to '', then the actual Content-Type in header is , multipart/form-data; boundary=----WebKitFormBoundary76s9Cg74EW1B94D9 as I mentioned at the first.
You can see there is a comma and a space before the multipar/form-data. I have no idea where this comma come from. But anyway, when I remove the comma and space, everything just works fine!