RE: How to interact with discourse platform using REST API's

then no problem you can directly store user info in the session to access the user info through the site. good.

1 Like

Is there a way to login user using API, since I cannot find password in the user data in the documentation or do I need to implement a local database for managing and retrieving user information.

var https = require(“http”);
var querystring = require(‘querystring’);

secret= {“url”: “http://localhost:9292/","key”: “1605437245731e6a74797ba82e34f37ed21038b3b2102dd6c929fd6c437b92bd”}

var json_data = null;

function UserLogin(userName,password){
const url=secret.url+‘session’;

var data={
“login”: userName,
“password”: password,
“second_factor_method”: 1
};

data=querystring.stringify(data);

const options={
method:‘POST’,
headers:{‘Api-Key’: secret.key ,‘Api-Username’: ‘siddhudhangar’}
};

var json_data = null
var request=https.request(url,options,function(response){
console.log(response.statusCode);
if(response.statusCode===200){
var body=‘’;
var result=‘’;
response.on(‘data’,function(chunk){
body+=chunk;
});
response.on(‘end’,function(){
result=JSON.parse(body);

    console.log(result);
    json_data = result

   });
 }else{
 	console.log('no');   
   }

});
request.write(data);
request.end();
return json_data;
}

UserLogin(“siddhudhangar@gmail.com”,“siddhudhangar123456”);

Try out above code then you can easily check whether user credentials are valid or not.

How i found out the login url i.e t2.metastudio.org/session/ using browsers network tool where you can see which url discourse is using and what params are being used etc. Try to learn browsers network tool because it is very important while developing apis mostly.
all discourse api urls are not available on discourse docs website. you need to do some reverse engineering to find out some apis particularly which are not available on discourse docs website.

some urls for your references:

https://meta.discourse.org/t/why-isnt-the-discourse-api-fully-documented/138265

1 Like

Thanks for the help.

Registering the user
200
{
success: true,
active: true,
message: ‘Your account is activated and ready to use.’,
user_id: 1094
}
yes
But while loggin in I get:-
200
{
error: “You can’t log in yet. We sent an activation email to you. Please follow the instructions in the email to activate your account.”,
reason: ‘not_activated’,
sent_to_email: ‘test1@gmail.com’,
current_email: ‘test1@gmail.com’
}

How to resolve the issue?

glab-Latitude-3540 Desktop # node react.js

{ success: true,
  active: true,
  message: 'Your account is activated and ready to use.',
  user_id: 1097 }
1097

{ error:
   'You can\'t log in yet. We sent an activation email to you. Please follow the instructions in the email to activate your account.',
  reason: 'not_activated',
  sent_to_email: 'siddhdhangar1@gmail.com',
  current_email: 'siddhdhangar1@gmail.com' }

when ran the code i was also facing the same issue. even i checked in users setting where i noticed that user got activated correctly but when we try to login using api it is showing me that account is not activated.

so we can do one thing here you try to remove the active and approved keys from dictionary object as shown below:
var data={
“name”: name,
“email”: email,
“password”: password,
“username”: userName,
// “active”: true,
// “approved”: true,
“user_fields[1]”: “Student”
};

once user account is created by api, then user account will not be activated until user confirms their the email id. once user confirms email id then user can login using user interface which you created already. i tested this functionality it is working fine in my local system. but on t2.metastudio.org site there it is not working because there email setting is disabled so email can be sent to users using api there. i will tell surendra to activate email so that we can test user registration part using api. right. Once he activates the email i will inform you. then you can test it again.

let me know if you have any query.

1 Like

Sir can you please reconfirm API endpoints for Registering and Validating Users?
The problem is that users registered from our APP cannot login to t2.metastudio.org and vice versa.

The endpoint I am using are
https://t2.metastudio.org/users/ for registering
https://t2.metastudio.org/session/ for verifying user
https://t2.metastudio.org/users/userName for getting user info

Thanks in advance

Ok. No need to say thanks. i will check these api endpoints again and let you know.

app.post('/register', function (req, res) {
  let user=req.session.user;
  if(user){
    res.redirect('/home');
    return;
  }else{
  if (req.body.hasOwnProperty('signup')) {
    if(req.body.pass1.length <10){
      res.render('register.ejs',{status:'Password should be atleast 10 characters long'});
    }
    else{
    var new_user=new func.getUser(req.body.email, md5(req.body.pass1), req.body.name, req.body.username1, req.body.identity);
    func.addNewUser(req,res,new_user.name,new_user.email,new_user.password,new_user.userName,new_user.identity);
    }
  } else if (req.body.hasOwnProperty('login')) {
    var curr_user = func.resetCurrUser();
    curr_user.userName = req.body.username2;
    curr_user.password = req.body.pass2;
    //curr_user.password = md5(req.body.pass2);
    func.verifyUser(req,res,curr_user.userName,curr_user.password);
  } else if (req.body.hasOwnProperty('forgot')) {
    res.send('forgot password page');
  } else {
    res.send('Error Occured');
  }
}
});

Hi,
i commented one line from above code. you made one mistake there that you are calling one md5 function for generating the md5 hash from the given plain text password. but what is happening right now is when user provides username and password(plain text password) for authentication, the same details which are username and password (plain text password) need to be passed to the post api.

1 Like

Got the error

I took clone of your github repo from GitHub - BirAnmol14/PS1-2020: A light weight progressive web app to work with metastudio.org in my local system. there it was working fine. Can you tell me what error exactly you are getting ?

I resolved the error

1 Like

Sir, kindly suggest a way we should go about implementing the chat page. We can uses private-messages and private-messages-sent end points but then it wont show all user activity. We can reverse engineer the notifications to get all activity for the user but then sent messages are left out. Kindly help out a bit, as we are stuck with this part.

Hi Bir,

As you mentioned you were able to get the messages using private-messages endpoint which is defined below

let username = “siddhu_dhangar”
var URL = https://metastudio.org/topics/private-messages/${username}.json;

after getting all the inbox messages json data in which you will get all the topics.

then try to get the each topics data using topic api endpoint as defined below.

const slug = “re-how-to-interact-with-discourse-platform-using-rest-apis”
const topic_id = “3940”
var URL = https://metastudio.org/t/${slug}/${topic_id}.json

then accordingly, you can get the sent messages info.

still you have doubt then let me know.

1 Like

Sir can you explain how to generate topic id while creating a topic?

Use below url for your reference. it will resolve your doubt.

https://docs.discourse.org/#tag/Posts/paths/~1posts.json/post

Below i showed you how to use post topic api for creating new topic.

Create a single topic:

curl -X POST “https://metastudio.org/posts.json”
-H “Content-Type: multipart/form-data;”
-H “Api-Key: 91798a8f80c6943ead9c7ab19ad3c17f54283rtrtwwae2a854910d3a1ded14773cf”
-H “Api-Username: username”
-F “title=new topic creating for testing”
-F “raw=desc of new topic creating for testing”
-F “archetype=regular”
-F “category=5”

If you use this post topic api, in output you will get topic_id etc. info.

1 Like
function create_topic(req,res){
    var title=req.body.title;
    var category=req.body.category;
    var desc=req.body.desc;
    var url=secrets.url+'/posts.json';
    var options={
      method:"POST",
      headers:{
      'Api-Key': secrets.key,
      'Api-Username': 'system',
      'Content-Type': 'application/json'
      }
    };
    var data1= { "title": title,
      "raw": desc,
      "category": category,
      "archetype": "regular"
    };
    var request=https.request(url,options,(response)=>{
        console.log(response.statusCode);
        if(response.statusCode===200){
          var body='';
          response.on('data',(data)=>{
            body+=data;
          });
          response.on('end',()=>{
            body=JSON.parse(body);
            console.log(body);
            res.redirect('/post/t/'+body.topic_slug+'/'+body.topic_id+'/1');
          });
        }
    });
    request.write(querystring.stringify(data1));
    request.end();
}

This is the function I wrote. This gives statusCode 400, on changing content type to multipart/form-data, it gives status 422.
Kindly help.

const https = require(‘https’)
const querystring = require(‘querystring’);

var secrets= {“url”: “https://t2.metastudio.org”,“key”: “api_key”}

function create_topic(title,category_id,desc){
var title=title;
var category=category_id;
var desc=desc;
var url=secrets.url+‘/posts.json’;
var options={
method:“POST”,
headers:{
‘Api-Key’: secrets.key,
‘Api-Username’: ‘Siddhu_Dhangar’,
// ‘Content-Type’: ‘application/json’
}
};
var data1= { “title”: title,
“raw”: desc,
“category”: category_id,
“archetype”: “regular”
};
var request=https.request(url,options,(response)=>{
console.log(response.statusCode);
// console.log(response);
if(response.statusCode===200){
var body=‘’;
response.on(‘data’,(data)=>{
body+=data;
});
response.on(‘end’,()=>{
body=JSON.parse(body);
//console.log(body);
//res.redirect(‘/post/t/’+body.topic_slug+‘/’+body.topic_id+‘/1’);
});
}
});
request.write(querystring.stringify(data1));
request.end();
}
create_topic(“new topic for testing”,17,“desc of new topic for testing”); // 17 is a category id

I ran above code it gave me 200 response. it created topic successfully. if you ran the same code again it gave me 422 response because topic already existed there.

Try this code and let me know if you have any doubt.

1 Like

Is there a way to know if a user can reply to a specific topic, for example I can reply to topics which are visible under latest topics but I cannot reply to topics of NMS_Jaipur ?

For ALL api interaction, we are passing system username parameter. and system is a admin user. so in security setting of category, admins group needs to be added. so i added admins group there as you can see in above image. now system user is able to create , reply or see the topic. one more thing that membership of user needs to be checked like if user is a member of that group, then user can create topic there otherwise cant create topic. so now can you check once whether you are able to create topic or not into the NMS jaipur?.