How to login flutter app using drupal 7 as backend

0

Edit 1

I have login page where I am sending username and password to get session Id and cache the session ID and proceed to home page when session Id is cached.But when I am sending data its returning error as below, but when i am sending requesting for login from postman app it works fine and returns the session ID. The same url is not working app but works fine in Postman app

import 'dart:io';

import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:home_screen.dart';
import 'package:../model/loginrequest.dart';
//import 'package:../model/loginrequesttoken.dart';
import 'package:path_provider/path_provider.dart';


class LoginPage extends StatefulWidget {
  static String tag = 'login-page';
  @override
  _LoginPageState createState() => new _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
//  LoginRequestData _loginData = LoginRequestData();

  bool _validate = false;
  bool _obscureText = true;
  var username, password;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // backgroundColor: Colors.white,
      body: SingleChildScrollView(
        child: Container(
          color: Colors.lightGreen[500],
          child: Column(
            children: <Widget>[
              Center(
                child: Container(
                  width: MediaQuery
                      .of(context)
                      .size
                      .width,
                  height: MediaQuery
                      .of(context)
                      .size
                      .height / 2.5,
                  decoration: BoxDecoration(
                      gradient: LinearGradient(
                        // begin: Alignment.topCenter,
                        // end: Alignment.bottomCenter,
                          colors: [
                            Color(0xFFFFFFFF),
                            Color(0xFFFFFFFF),
                          ]
                      ),
                      borderRadius: BorderRadius.only(
                          bottomLeft: Radius.circular(90)
                      )
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Align(
                        alignment: Alignment.center,
                        child: Image.asset('images/ic_launcher1.png'),
                      ),
                    ],
                  ),
                ),
              ),
              Center(
                  child: SingleChildScrollView(
                    child: new Form(
                      key: _formKey,
                      autovalidate: _validate,
                      child: _getFormUI(),
                    ),
                  )
              )

            ],
          ),
        ),
      ),
    );
  }

  Widget _getFormUI() {
    return new Column(
      children: <Widget>[
        SizedBox(height: 24.0),
        Center(
          child: Text('Login',
            style: TextStyle(fontSize: 25,
                fontWeight: FontWeight.bold,
                color: Colors.white),),
        ),
        new SizedBox(height: 25.0),
        new TextFormField(
          keyboardType: TextInputType.emailAddress,
          autofocus: true,
          decoration: InputDecoration(
            hintText: 'Username',
            contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
            border:
            OutlineInputBorder(borderRadius: BorderRadius.circular(32.0)),
          ),
          validator: _validateName,
          onSaved: (value) {
            username = value;
          },
        ),
        new SizedBox(height: 8.0),
        new TextFormField(
            autofocus: false,
            obscureText: _obscureText,
            keyboardType: TextInputType.text,
            decoration: InputDecoration(
              hintText: 'Password',
              contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
              border:
              OutlineInputBorder(borderRadius: BorderRadius.circular(32.0)),
              suffixIcon: GestureDetector(
                child: Icon(
                  _obscureText ? Icons.visibility : Icons.visibility_off,
                  semanticLabel:
                  _obscureText ? 'show password' : 'hide password',
                ),
              ),
            ),
            validator: _validatePassword,
            onSaved: (String value) {
              password = value;
            }
        ),
        new SizedBox(height: 15.0),
        new Padding(
          padding: EdgeInsets.symmetric(vertical: 16.0),
          child: RaisedButton(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(24),
            ),
            onPressed: () {
              _submit();
//              Navigator.of(context).pushReplacementNamed('/home');
            },
            padding: EdgeInsets.all(12),
            color: Colors.black54,
            child: Text('Log In', style: TextStyle(color: Colors.white)),
          ),
        ),
        new FlatButton(
          child: Text(
            'Forgot password?',
            style: TextStyle(color: Colors.black54),
          ),
          onPressed: () {},
        ),
        new FlatButton(
          onPressed: _sendToRegisterPage,
          child: Text('Not a member? Sign up now',
              style: TextStyle(color: Colors.black54)),
        ),
        Text(''),
        Text(''),
        Text(''),
      ],
    );
  }

  _sendToRegisterPage() {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => HomeScreen()),
    );
  }

  String _validateName(String value) {
    if (value.isEmpty) {
      return "Username is Required";
    } else {
      username = value.toString();
    }
  }

  String _validatePassword(String value) {
    if (value.isEmpty) {
      return "Password is Required";
    } else {
      password = value.toString();
    }
  }

  _submit() {
    if (_formKey.currentState.validate()) {
      _formKey.currentState.save();
      print("Username ${username}");
      print("Password ${password}");
      return SessionId();
    } else {
      setState(() {
        bool _validate = false;
      });
    }
  }

  LoginRequestData _loginData = LoginRequestData();

  final Dio _dio = Dio();
  PersistCookieJar persistentCookies;
  final String url = "https://www.xxxx.in/rest/user/login.json";

  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }

  Future<Directory> get _localCoookieDirectory async {
    final path = await _localPath;
    final Directory dir = new Directory('$path/cookies');
    await dir.create();
    return dir;
  }

  Future<String> getCsrftoken() async{
    try {
      String csrfTokenValue;
      final Directory dir = await _localCoookieDirectory;
      final cookiePath = dir.path;
      persistentCookies = new PersistCookieJar(dir: '$cookiePath');
      persistentCookies.deleteAll(); //clearing any existing cookies for a fresh start
      _dio.interceptors.add(
          CookieManager(persistentCookies) //this sets up _dio to persist cookies throughout subsequent requests
      );
      _dio.options = new BaseOptions(
        baseUrl: url,
        contentType: ContentType.json,
        responseType: ResponseType.plain,
        connectTimeout: 5000,
        receiveTimeout: 100000,
        headers: {
          HttpHeaders.userAgentHeader: "dio",
          "Connection": "keep-alive",
        },
      ); //BaseOptions will be persisted throughout subsequent requests made with _dio
      _dio.interceptors.add(
          InterceptorsWrapper(
              onResponse:(Response response) {
                List<Cookie> cookies = persistentCookies.loadForRequest(Uri.parse(url));
                csrfTokenValue = cookies.firstWhere((c) => c.name == 'csrftoken', orElse: () => null)?.value;
                if (csrfTokenValue != null) {
                  _dio.options.headers['X-CSRF-TOKEN'] = csrfTokenValue; //setting the csrftoken from the response in the headers
                }
                print(response);
                return response;
              }
          )
      );
      await _dio.get("https://www.xxxx.in/rest/user/login.json");
      print(csrfTokenValue);
      return csrfTokenValue;
    } catch (error, stacktrace) {
      print("Exception occured: $error stackTrace: $stacktrace");
      return null;
    }
  }

   SessionId() async {
     try {
       final csrf = await getCsrftoken();
       FormData formData = new FormData.from({
         "username": "${_loginData.username}",
         "password": "${_loginData.password}",
         "csrfmiddlewaretoken" : '$csrf'
       });
       Options optionData = new Options(
         contentType: ContentType.parse("application/json"),
       );
       Response response = await _dio.post("https://www.xxxx.in/rest/user/login", data: formData, options: optionData);
       print(response.statusCode);
     } on DioError catch(e) {
       if(e.response != null) {
         print( e.response.statusCode.toString() + " " + e.response.statusMessage);
         print(e.response.data);
         print(e.response.headers);
         print(e.response.request);
       } else{
         print(e.request);
         print(e.message);
       }
     }
     catch (error, stacktrace) {
       print("Exception occured: $error stackTrace: $stacktrace");
       return null;
     }
   }
}

Error

Exception occured: DioError [DioErrorType.RESPONSE]: Http status error [404] stackTrace: #0      Dio._makeRequest (package:dio/src/dio.dart:799:16)
I/flutter (22859): <asynchronous suspension>
I/flutter (22859): #1      Dio._request.<anonymous closure>.<anonymous closure> (package:dio/src/dio.dart:711:22)
I/flutter (22859): #2      _rootRunUnary (dart:async/zone.dart:1132:38)
I/flutter (22859): #3      _CustomZone.runUnary (dart:async/zone.dart:1029:19)
I/flutter (22859): #4      _FutureListener.handleValue (dart:async/future_impl.dart:126:18)
I/flutter (22859): #5      Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:639:45)
I/flutter (22859): #6      Future._propagateToListeners (dart:async/future_impl.dart:668:32)
I/flutter (22859): #7      Future._complete (dart:async/future_impl.dart:473:7)
I/flutter (22859): #8      _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
I/flutter (22859): #9      _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:28:18)
I/flutter (22859): #10     _completeOnAsyncReturn (dart:async-patch/async_patch.dart:294:13)
I/flutter (22859): #11     Dio._executeInterceptors (package:dio/src/dio.dart)
I/flutter (22859): <asynchronous suspension>
I/flutter (22859): #12     Dio._request.<anonymous
I/flutter (22859): 403 : The username  has not been activated or is blocked.
I/flutter (22859):  ["The username <em class=\"placeholder\"></em> has not been activated or is blocked."]
I/flutter (22859): connection: Keep-Alive
I/flutter (22859): keep-alive: timeout=5, max=99
I/flutter (22859): cache-control: no-cache, must-revalidate
I/flutter (22859): date: Tue, 06 Aug 2019 05:23:58 GMT
I/flutter (22859): vary: Accept
I/flutter (22859): content-length: 87
I/flutter (22859): content-type: application/json
I/flutter (22859): x-content-type-options: nosniff, nosniff
I/flutter (22859): server: Apache/2.4.18 (Ubuntu)
I/flutter (22859): expires: Sun, 19 Nov 1978 05:00:00 GMT
I/flutter (22859): Instance of 'RequestOptions'

Need to login the app using these both codes

authentication
flutter
drupal-7
asked on Stack Overflow Aug 2, 2019 by Monty • edited Aug 6, 2019 by Monty

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0