How do I log into members area on my website from the app?

Hi, basically, i run a wildlife travel website. I have been building an mit app inventer app as an accompaniment to the website. (the website is to do with wildlife watching, so is usually done far from a computer).

On the website, i have a series of members areas, for various groups, using a plugin called armember.

I am looking for a way to create a login, into these areas on the website from the app, so that members can access restricted content such as live sightings maps.

How would i do this? Any thoughts?

This will depend on the requirements of your login process on your website. Can users just bring up the website login area on their app with a webview ?

That is certainly a possibility - i have done that elsewhere in the app. Still there would be issues with this.

It being a wildlife orientated site, many places where people might want to access member features, are likely to be remote. Having said that, i think your comment has given me an idea of a different way to have it work

Sounds like you want to create a delayed access approach. Users store data in the app when in the field, and once they return to civilization and have wifi, they can then connect to their members area and upload the data?

Hi, sort of - i have created a process to take sightings - they save on a file, and when data is available they transfer to a Google sheet - from which the sightings map reads them.

I think this thread is making it clear that i should do the rest on the website, where i have a plugin to handle it.

I need to work out access rules, but that is a different issue.

It would be great to be able to allow people to opt for the maps they want in the app - but i think it can be done simply within the website, so perhaps not even bother with that.

Clearly unnecessary complicating it.

Thanks all

On your website:

  • Create a PHP script at https://yourwebsite.com/api/login.php that:
    • Receives username and password via POST.
    • Checks credentials against aMember.
    • Returns JSON: { "status": "success", "token": "abc123" } on success or { "status": "fail" } on failure.

In App Inventor app:

  • Use the Web component:
    • URL: https://yourwebsite.com/api/login.php
    • Method: POST
    • Body: username and password fields.
  • Handle the response:
    • If success, store the token.
    • Use the token for subsequent requests to access restricted content.

Right, I'll have a long look in the next few days.

Just to complicate things, i have a few different members areas (catering for very different users), from travelers to those living in wild places etc. Can you give me an idea how i would edit your system/ code? I will have a look at it over the next couple of days

In such case, Add a field in your user table for user type or group (e.g., user_role, membership_level, area).Do you have php knowledge? In our forum there is lot of suggestions are there with that code. I am sharing a little here. Kindly modify it according to your need.


PHP Example: Multi-Group Login API

This script authenticates users, retrieves their group, and returns a JWT token containing user info.

Note: For production, use a secure method for password hashing (e.g., password_hash()) and a proper JWT library.

Complete login.php:

<?php
// login.php

// Database connection (replace with your own credentials)
$conn = new mysqli('localhost', 'db_user', 'db_password', 'db_name');

if ($conn->connect_error) {
    die(json_encode(['status' => 'error', 'message' => 'DB connection failed']));
}

// Get POST data
$username = $_POST['username'];
$password = $_POST['password'];

// Prepare statement to prevent SQL injection
$stmt = $conn->prepare("SELECT id, password, user_role FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows == 1) {
    $user = $result->fetch_assoc();

    // Verify password (assuming passwords are hashed)
    if (password_verify($password, $user['password'])) {
        // Generate JWT token
        require 'jwt.php'; // Include JWT functions or library

        $payload = [
            'user_id' => $user['id'],
            'role' => $user['user_role'],
            'exp' => time() + 3600 // Token expires in 1 hour
        ];

        $token = generate_jwt($payload);

        echo json_encode([
            'status' => 'success',
            'token' => $token,
            'role' => $user['user_role']
        ]);
    } else {
        echo json_encode(['status' => 'fail', 'message' => 'Invalid password']);
    }
} else {
    echo json_encode(['status' => 'fail', 'message' => 'User not found']);
}

$conn->close();

// Example JWT generation function (use a library for production)
function generate_jwt($payload) {
    $header = json_encode(['alg' => 'HS256', 'typ' => 'JWT']);
    $base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));

    $payloadJson = json_encode($payload);
    $base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payloadJson));

    $secret = 'your_secret_key'; // Keep this safe
    $signature = hash_hmac('SHA256', $base64UrlHeader . '.' . $base64UrlPayload, $secret, true);
    $base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));

    return $base64UrlHeader . '.' . $base64UrlPayload . '.' . $base64UrlSignature;
}
?>

MIT App Blocks: Login and Access Control

1. Login Block

  • Use the Web component to send POST request to your PHP login script.
  • Store the token on success.
  • Use the token for subsequent requests.

Blocks:

  • Initialize: When user clicks login button:
    • Set Web URL to your API endpoint (e.g., https://yourwebsite.com/login.php)
    • Set Web Method: POST
    • Set Web Request Headers: Content-Type: application/x-www-form-urlencoded
    • Set Web Post Body: username and password fields
// Example pseudocode for blocks:

When ButtonLogin.Click:
    Web1.Url = "https://yourwebsite.com/login.php"
    Web1.PostText = "username=" + usernameTextBox.Text + "&password=" + passwordTextBox.Text
    Web1.Post()
  • When Web1.GotText:
If Web1.ResponseContent contains "status":"success":
    Extract token from response (use JSONTextDecode)
    Store token in TinyDB or variable
    Show message "Login successful"
Else:
    Show message "Login failed"

2. Accessing Protected Content

  • When requesting restricted content, send the token in headers or as a URL parameter.

Example:

// To get data:
Web2.Url = "https://yourwebsite.com/protected_content.php?token=" + storedToken
Web2.Get()
  • In the server script (protected_content.php), verify the token before serving content.

3. Token Verification (Server-side)

You’ll need a PHP script to verify JWT tokens sent from the app. For simplicity, this can decode and verify the token’s signature.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.